Title description:
My solution:
I originally forgot about the KMP algorithm. I reviewed it through this question.
Which calculates the next loop while (i <length-1), pay attention to need -1, because there is i ++ below, otherwise it will report an error
It took a long time to find the mistake here
class Solution {
//private:
// int next[];
public:
int* func(string needle){
int* next=new int[needle.length()];
int length=needle.length();
int i=0;
int j=-1;
next[0]=-1;
while(i<length-1){
if(j==-1 || needle[i]==needle[j]){
i++;
j++;
next[i]=j;
}
else j=next[j];
}
return next;
}
int strStr(string haystack, string needle) {
if(needle=="") return 0;
if(haystack==""&&needle!="") return -1;
if(haystack.length()<needle.length()) return -1;
int *next=func(needle);
int i=0,j=0;
int la=(int)haystack.length(),lb=(int)needle.length();
while(i<la&&j<lb){
if(j==-1 || haystack[i]==needle[j]){
i++;
j++;
}
else j=next[j];
}
return j==lb?i-j:-1;
}
};