int *Pref;
void Prefix(const string& P)//前缀函数
{
const int M = P.size();
Pref[0] = -1;
int k=-1;
for(int i=1; i<M; ++i)
{
while(k>-1 && P[k+1]!=P[i]) k = Pref[k];
if(P[k+1] == P[i]) ++k;
Pref[i] = k;
}
}
void KMP(const string& T, const string& P)
{
Prefix(P);
const int N = T.size(), M = P.size();
int k=-1;
for(int i=0; i<N; ++i)
{
while(k>-1 && P[k+1]!=T[i]) k = Pref[k];
if(P[k+1] == T[i]) ++k;
if(k == M-1)//已经匹配的字符数目
{
cout<<"Pattern \""<<P<<"\" Occurs with shift "<<i-k<<" in \""<<T<<"\""<<endl;
k = Pref[k];
}
}
}
void TestKMP()
{
const string T("abababacaba"), P("ababaca");
Pref = new int[P.size()];
KMP(T,P);
delete[] Pref;
}
KMP算法代码
最新推荐文章于 2024-04-15 15:59:11 发布