题目
KMP匹配
思路
实现
class Solution {
public:
int strStr(string haystack, string needle) {
int len_ss = haystack.size();
int len_pp = needle.size();
if (len_pp == 0)
return 0;
vector<int> next(len_pp);
for(int i = 1, j = 0; i < len_pp; ++i){
while(j && needle[i] != needle[j])
j = next[j - 1];
if (needle[i] == needle[j])
++j;
next[i] = j;
}
for(int i = 0, j = 0; i < len_ss; ++i){
while(j && haystack[i] != needle[j])
j = next[j - 1];
if (haystack[i] == needle[j])
++j;
if (j == len_pp)
return i - len_pp + 1;
}
return -1;
}
};