Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
注意needle为“”返回的是0.
一定要熟悉KMP算法!
class Solution {
public:
int strStr(string haystack, string needle) {
int lenn = needle.size();
int lenh = haystack.size();
if (lenn == 0){
return 0;
}
if (lenn > lenh){
return -1;
}
vector<int> next(lenn);
makeNext(needle, next);
int k = 0;
for (int i = 0; i < lenh; i++){//i=0
while (k>0 && haystack[i] != needle[k]){
k = next[k - 1];
}
if (haystack[i] == needle[k]){
k++;
}
if (k == lenn){
return i - k + 1;
}
}
return -1;
}
private:
void makeNext(string needle, vector<int>&next){
int len = needle.size();
next[0] = 0;
int k = 0;//
for (int i = 1; i < len; i++){//i=1;
while (k>0&&needle[i] != needle[k]){
k = next[k - 1];
}
if (needle[i] == needle[k]){
k++;//
}
next[i] = k;
}
}
};