Descripción del título:
Mi solucion:
Originalmente olvidé el algoritmo KMP. Lo revisé a través de esta pregunta.
Que calcula el siguiente ciclo mientras (i <longitud-1), preste atención a la necesidad -1, porque hay i ++ a continuación, de lo contrario, informará un error
Tomó mucho tiempo encontrar el error aquí
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;
}
};