对应题目:力扣28题
class Solution {
public:
//kmp算法
void getNext(int* next, const string& s) {
//前缀结尾
int frontLast=0;
//后缀结尾
int backLast=1;
next[0]=0;
for(backLast;backLast<s.size();backLast++){
while(frontLast>0&&s[backLast]!=s[frontLast])//动态规划持续回溯
frontLast=next[frontLast-1];//找到backLast-1的最大公共前后缀
if(s[backLast]==s[frontLast])//包含本身元素,最长公共前后缀长度加1
frontLast++;
next[backLast]=frontLast;
}
}
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-j+1;
}
return -1;
}
};