C++——KMP算法

代码示例:

class Solution {
public:
    void getNext(int* next, const string& s) {
        int j = 0;                          // 初始化;i为后缀末尾; j为前缀末尾;
        next[0] = 0;
        for(int i = 1; i < s.size(); i++) 
        {
            while (j > 0 && s[i] != s[j])  // 前后缀不相同
            {
                j = next[j - 1];
            }
            if (s[i] == s[j])              // 前后缀相同
            {
                j++;
            }
            next[i] = j;                   // next
        }
    }
    int strStr(string haystack, string needle) {
        if (needle.size() == 0) 
        {
            return 0;
        }
        int next[needle.size()];
        getNext(next, needle);
        int j = 0;
        for (int i = 0; i < haystack.size(); i++) 
        {
            while(j > 0 && haystack[i] != needle[j]) 
            {
                j = next[j - 1];
            }
            if (haystack[i] == needle[j])
            {
                j++;
            }
            if (j == needle.size() ) 
            {
                return (i - needle.size() + 1);
            }
        }
        return -1;
    }
};
posted @ 2022-11-01 09:50  香花草的味道  阅读(37)  评论(0)    收藏  举报