KMP
注意nextval数组的长度,如果过短会执行错误(数组越界)
class Solution {
public:
int nextval[100005];
void get_nextval(string s) {
int i = 0, x = -1; nextval[i] = x;
while (i < s.size()) {
if (x == -1 || s[i] == s[x]) {
++i, ++x;
if (s[i] == s[x]) nextval[i] = nextval[x];
else nextval[i] = x;
}
else x = nextval[x];
}
}
int strStr(string haystack, string needle) {
get_nextval(needle);
int i = 0, j = 0;
while (i < (int)haystack.size() && j < (int)needle.size()) {
if (j == -1 || haystack[i] == needle[j]) ++i, ++j;
else j = nextval[j];
}
if (j >= needle.size()) return i - needle.size();
else return -1;
}
};