在写KMP算法时,把i<S.length()&&j<T.length()直接放到了while()中,当j为负数时,发现循环进不去:
void KMP(string S,string T){int i=0,j=0;while(i<S.length()&&j<T.length()){cout<<"i="<<i<<" j="<<j<<endl;if(j==-1||S[i]==T[j]){i++;j++;}else{j=nextj[j];}}cout<<"出while:"<<"i="<<i<<" j="<<j<<endl;if(j>=T.length()) cout<<i-T.length()+1<<endl;else cout<<"-1"<<endl;
}
当j==-1时,发现while()循环进不去了!
原因就是 s.length()返回的类型是unsigned int,而j为负数,超出了unsigned int的范围,所以这两处会有问题:
改正后:
void KMP(string S,string T){int i=0,j=0;int len1=S.length(),len2=T.length();while(i<len1&&j<len2){cout<<"i="<<i<<" j="<<j<<endl;if(j==-1||S[i]==T[j]){i++;j++;}else{j=nextj[j];}}if(j>=len2) cout<<i-len2+1<<endl;else cout<<"-1"<<endl;
}