class Solution {
public:
vector<int> getNext(string str) {
int len = str.size();
vector<int> next(len+1);
int ii = 0, jj = -1;
next[0] = -1;
while(ii < len) {
if(jj == -1 || str[ii] == str[jj]) next[++ii] = ++jj;
else jj = next[jj];
}
return next;
}
int strStr(string haystack, string needle) {
if(needle == "") return 0;
vector<int> next = getNext(needle);
int len_haystack = haystack.size();
int len_needle = needle.size();
int ii = 0, jj = 0;
while(ii < len_haystack && jj < len_needle) {
if(jj == -1 || haystack[ii] == needle[jj]) {
++ii;
++jj;
}
else jj = next[jj];
}
if(jj == len_needle) return ii - jj;
return -1;
}
};
【leetcode 字符串 KMP算法 C++】28. Implement strStr()
猜你喜欢
转载自blog.csdn.net/m0_37454852/article/details/113701644
今日推荐
周排行