タイトルの説明:
私の解決策:
もともとKMPのアルゴリズムを忘れていたので、この質問で見直しました。
次のループを計算します(i <length-1)、下にi ++があるため、必要性-1に注意してください。それ以外の場合はエラーを報告します
ここで間違いを見つけるのに長い時間がかかりました
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;
}
};