【LeetCode-简单题 KMP匹配算法】28. 找出字符串中第一个匹配项的下标

题目

在这里插入图片描述

方法一:常规做法 一次一次截取再做比较

在这里插入图片描述

class Solution {
    
    
    public int strStr(String haystack, String needle) {
    
    
        int haylen = haystack.length();
        int neelen = needle.length();
        if(haylen < neelen) return -1;
        for(int i = 0; i <haylen-neelen+1;i++){
    
    
            if(needle.equals(haystack.substring(i,i+neelen))) return i;
        }
        return -1;
    }
}

方法二:KMP匹配算法

主要分为两步

  1. 第一步:根据匹配串构建next前缀数组(不减-1的版本)
    在这里插入图片描述
    在这里插入图片描述

  2. 第二步:根据构建好的next数组,去文本串里面进行匹配
    在这里插入图片描述

在这里插入图片描述

class Solution {
    
    
    public int strStr(String haystack, String needle) {
    
    
        int[] next  = getNext(needle);
        int j = 0;//前缀匹配过程
        for(int i = 0 ;i<haystack.length();i++){
    
    
            //注意这里是while  不是if  while是需要一直找下去  直到找到相同前缀
            while(j>0&&haystack.charAt(i) != needle.charAt(j))  j = next[j-1];
            if(haystack.charAt(i) == needle.charAt(j)) j++;
            if(j == next.length) return i - next.length +1;
        }
        return -1;
    }
    //构造next前缀表数组
    public int[] getNext(String s){
    
    
        int[] next = new int[s.length()];
        int j = 0;
        next[0] = j;//初始化 0 号位置的相同前后缀  肯定就是0 
        for(int i = 1 ;  i<s.length() ; i++){
    
    
             //注意这里是while  不是if  while是需要一直找下去  直到找到相同前缀
            while(j>0 &&s.charAt(i) != s.charAt(j)){
    
    
                    j = next[j-1];//一直找下去  直到找到相同前后缀  否则就是直接归0
            }
            if(s.charAt(i) == s.charAt(j)){
    
    //若相等 前缀末尾j++  然后再赋给前缀末尾i位置的next数组
                j++;
            }
            next[i] = j;
        }
        return next;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_45618869/article/details/132915847