KMP (leetcode 28)

class Solution {
public:
    int strStr(string haystack, string needle) {
        int n = haystack.size();
        int m = needle.size();
        if(m == 0) return 0;
        if(n == 0) return -1;
        vector<int> suffix(m,0);
        for(int i = 1; i<m ;i++){
            int j = suffix[i-1];
            while(j>=1 && needle[i]!=needle[j]){
                j = suffix[j-1];
            }
            suffix[i] = j + (needle[i]==needle[j]);
        }
        // for(auto x:suffix)cout<<x<<" ";
        vector<int> dp(n,0);

        dp[0] = (haystack[0] == needle[0]);
        if(m == 1&& dp[0] == 1) return 0;

        for(int i = 1; i<n; i++){
            int j = dp[i-1];
            while(j>0 && haystack[i] != needle[j]){
                j = suffix[j-1];
            }
            dp[i] = j + (haystack[i] == needle[j]);
            if(dp[i] == needle.size()) return i-m+1;
        }
        return -1;

    }
};

 

posted on 2022-06-23 22:39  xhskjjmc  阅读(21)  评论(0)    收藏  举报