KMP算法之一
#include <iostream> //KMP算法是一种改进的字符串匹配算法,复杂度为O(n)
using namespace std;
char A[500000],B[500000]; //A是主串,B是子串,查询B串在A串的哪些地方出现
int n,m,next[500000]; //n,m分别是A,B的串长度,注意A,B的下标是从1开始的
void get_next()
{
next[1]=0;
int j=0;
for(int i=2;i<=m;++i)
{
while(j>0&&B[j+1]!=B[i])
j=next[j];
if(B[j+1]==B[i])
j=j+1;
next[i]=j;
}
}
void kmp()
{
int j=0;
for(int i=1;i<=n;++i)
{
while(j>0&&B[j+1]!=A[i])
j=next[j];
if(B[j+1]==A[i])
j=j+1;
if(j==m)
{
cout<<"Pattern occurs with shift "<<i-m<<endl;
j=next[j];
}
}
cout<<endl;
}
int main()
{
while(scanf("%s %s",A+1,B+1)!=EOF)
{
for(n=0;A[n+1]!='\0';++n);
for(m=0;B[m+1]!='\0';++m);
get_next();
kmp();
}
return 0;
}
//http://www.matrix67.com/blog/archives/115
/*
sample:
ababaab (A串)
ab (B串)
Pattern occurs with shift 0
Pattern occurs with shift 2
Pattern occurs with shift 5
*/