题目链接
class Solution {
public:
int strStr(string haystack, string needle) {
int m = needle.length();
if (m == 0) {
return 0;
}
vector<int> next = getNext(needle);
int j = 0, i = 0;
for (;i < haystack.length(); i++) {
while (j > 0 && haystack[i] != needle[j]) {
j = next[j - 1];
}
if(haystack[i] == needle[j]) {
j++;
}
if (j == m ) {
return i - m + 1;
}
}
return -1;
}
vector<int> getNext(string needle) {
int n = needle.length();
int j = 0;
vector<int> next(n, 0);
for (int i = 1; i < n; i++) {
while(j > 0 && needle[j] != needle[i]) {
j = next[j - 1];
}
if(needle[j] == needle[i]) {
j++;
}
next[i] = j;
}
return next;
}
};

总结
- kmp算法就是求一个前缀表,比较最长前后缀
- 在进行字符串匹配的时候,从失配位置的前一个位置的next值开始比较