[LeetCode-Simple Question KMP Matching Algorithm] 28. Find the subscript of the first matching item in the string

topic

Insert image description here

Method 1: The conventional approach is to intercept and compare the images one at a time.

Insert image description here

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;
    }
}

Method 2: KMP matching algorithm

Mainly divided into two steps

  1. Step 1: Construct the next prefix array based on the matching string (version without minus 1)
    Insert image description here
    Insert image description here

  2. Step 2: Match the text string according to the constructed next array.
    Insert image description here

Insert image description here

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;
    }
}

Guess you like

Origin blog.csdn.net/weixin_45618869/article/details/132915847