**Leetcode 28. Implement strStr() | KMP

https://leetcode.com/problems/implement-strstr/description/

最近听说有面试遇到KMP的,赶紧补一下

讲解看这里: 如何更好的理解和掌握 KMP 算法? - 海纳的回答 - 知乎https://www.zhihu.com/question/21923021/answer/281346746

然后代码结合上面链接以及吉林大学模板吧

void init_next(const char *pat, int n, int*next) {
    // cout << next[0] << endl;
    for (int i =  0; i < n; i++) {
        next[i] = -1;
    }
    int i = 0, j = -1, patlen = strlen(pat);
    while (i < patlen  ) {
        if ( j == -1 || pat[i] == pat[j] ) {
            ++i;
            ++j;
            next[i] = j;
            
        } else {
            j = next[j];
        }
    }
}

int kmp(string s, string pat, int*next) {
    int i = 0, j = 0;

    while (i < s.size() && j < pat.size() )  {
        if (s[i] == pat[j]) {
            i++;
            j++;
        } else {
            if (j == 0) {
                ++i;    
            } else {
                j = next[j] ;
            }
        }
    }
    
    return j < pat.size() ? -1 : i - pat.size();
}

class Solution {
public:
    int strStr(string haystack, string needle) {
        int next[needle.size()+1];
        init_next(needle.c_str(), needle.size(), next);
        return kmp(haystack, needle, next);
    }
};


猜你喜欢

转载自blog.csdn.net/u011026968/article/details/80152218