Description du titre:
Ma solution:
Au départ, j'avais oublié l'algorithme KMP. Je l'ai revu à travers cette question.
Ce qui calcule la boucle suivante tandis que (i <longueur-1), faites attention au besoin -1, car il y a i ++ ci-dessous, sinon il signalera une erreur
Il a fallu beaucoup de temps pour trouver l'erreur ici
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;
}
};