问题是在写KMP算法过程中出现的,但好像不是算法问题,先po出代码
#include<iostream>
#include<cstring>
using namespace std;
void Match_KMP(string T,string P)
{
//先找子串的NEXT数组
int next[P.length()];
next[0] = -1;
next[1] = 0;
int j = 1,k = 0,i;
while(j < P.length()){
if(P[k] == P[j] || k == -1)
next[++j] = ++k;
else{
k = next[k];
}
}
//开始查找
i = 0; j = 0;
while(i < T.length() && j < P.length()){
if(T[i] == P[i] || j == -1){
cout<<T[i]<<" "<<P[i];
i++;
j++;
}
else{
j = next[j];
//cout<<"j此时的值为:"<<j<<endl;
//cout<<"P.LEN此时的值为:"<<P.length()<<endl;
//cout<<(j < P.length());
//cout<<endl<<(i < T.length());
}
}
if(j < P.length())
cout<<0<<endl;
else
cout<<endl<<i<<endl;
}
int main()
{
cin>>father;
cin>>son;
Match_KMP(father,son);
return 0;
}

由于运行过程中用debug看,始终查找子串的while部分只进入了一次循环,所以在注释部分输出了一些结果,发现是第二个条件不
符合,但我的疑问是-1 < 3为什么输出结果是0呢?