Leetcode 28. Implement strStr()
https://leetcode.com/problems/implement-strstr/
class Solution {
public:
void KMP(string needle, vector<int> &nextval) {
nextval[0] = -1;//1长度没有真前后缀的公共部分
int x = -1;
for (int k = 1; k < needle.size(); ++k) {
//要等needle[0...k-1]和needle[0...x]匹配才行【x表示needle[0...k-2]的从大到小的真前后缀公共部分】
while (x!=-1 && needle[k-1] != needle[x]) {
x = nextval[x];
}
++x;
if (needle[x] == needle[k]) {//考虑是匹配needle[k]遇到的失配
nextval[k] = nextval[x];
}
else {
nextval[k] = x;
}
}
}
int strStr(string haystack, string needle) {
if (needle.empty()) return 0;
if (haystack.empty()) return -1;
/*
KMP算法
*/
vector<int> nextval(needle.size(), 0);
KMP(needle, nextval);
int x = 0;
for (int k = 0; k < haystack.size(); ++k) {
while (x != -1 && haystack[k] != needle[x]) {
x = nextval[x];
}
if (++x == needle.size()) return k + 1 - needle.size();
}
return -1;
}
};