#include<iostream>
#include<string>
using namespace std;
int *nextfun(string P){
int m = P.length();
int *ret = new int[m];
ret[0] = 0;
for(int i = 1 ; i < m ; i++){
int k = ret[i-1];
if(P[i] == P[k]){
ret[i] = k + 1;
}
else{
while(P[i]!=P[k] && k>0)
k = ret[k-1];
if(P[i] == P[k])
ret[i] = k + 1;
else
ret[i] = 0;
}
}
return ret;
}
int KMPStrMatch(string S,string P,int *N){
int slen = S.length(),plen = P.length();
if(slen < plen)
return -1;
int i,j=0;
for(i = 0 ; i < slen ; i++){
while(P[j] != S[i] && j > 0)
j = N[j-1];
if(P[j] == S[i])
j++;
cout<<"i="<<i<<";"<<"j="<<j<<endl;
if(j == plen)
return (i-j+1);
}
return -1;
}
int main(){
string S="abaabababba";
string P = "abaa";
int* a = nextfun(P);
for(int i = 0 ; i < 5 ; i++){
cout<<a[i]<<" ";
};
cout<<endl;
cout<<KMPStrMatch(S,P,a)<<endl;
}
KMP算法
最新推荐文章于 2023-04-09 17:43:52 发布