思路:KMP。获取next数组,next数组存的就是前后缀相等的最大长度,j表示前缀末尾,i表示后缀末尾.
题解c++:
class Solution {
public:
void getnext(int *next,const string &s)
{
int j = 0;
next[0] = 0;
for(int i = 1; i < s.size(); i++) {
while (j > 0 && s[i] != s[j]) {
j = next[j - 1];
}
if (s[i] == s[j]) {
j++;
}
next[i] = j;
}
}
int strStr(string haystack, string needle) {
if(needle.size()==0)
return 0;
int next[needle.size()];
getnext(next,needle);
int j=0;
for (int i = 0; i < haystack.size(); i++) {
while(j > 0 && haystack[i] != needle[j]) {
j = next[j - 1];
}
if (haystack[i] == needle[j]) {
j++;
}
if (j == needle.size() ) {
return (i - needle.size() + 1);
}
}
return -1;
}
};