class Solution {
public:
void findnextval(string needle,int nextval[]){
int j=0,k=-1;
nextval[0]=-1;
while(j<needle.length()-1){//此处一定要-1,因为在if中有j++后对next[j]赋值,不减一的话会数组溢出
if(k==-1 ||needle[j]==needle[k]){
k++;
j++;
if(needle[j]!=needle[k]){
nextval[j]=k;
}
else{
nextval[j]=nextval[k];
}
}
else{
k=nextval[k];
}
}
}
int strStr(string haystack, string needle) {
if(needle.length()==0){
return 0;
}
if(haystack.length()==0){
return -1;
}
int n=needle.length();//用来代表needle的长度,因为C++中不能数组长度不能和负数比较
//如果不写n,while就无法循环
int nextval[n];
findnextval(needle,nextval);
int i=0;
int j=0;
while(i<haystack.length() && j<n){
if(j==-1 || haystack[i]==needle[j]){
i++;
j++;
}
else{
j=nextval[j];
}
}
if(j>=needle.length()){
return i-needle.length();
}
return -1;
}
};
探索数组和字符串 实现strStr() KMP nextval算法解决
猜你喜欢
转载自blog.csdn.net/weixin_45221477/article/details/105254810
今日推荐
周排行