您的位置:首页 > 其它

KMP模板

2015-07-25 09:20 309 查看
#include <iostream>

#include<string.h>

#include<stdio.h>

using namespace std;

char s[1000001];

int next[10005];//next[i] 0-i字符串最大匹配数

/*

* next[]的含义:x[i-next[i]...i-1]=x[0...next[i]-1]

* next[i]为满足x[i-z...i-1]=x[0...z-1]的最大z值(就是x的自身匹配)next[i]=z;

*/

void getnext(char x[])

{

int i,j,m;

next[0]=0;

next[1]=0;

m=strlen(x);

for(i=1;i<m;i++)

{

j=next[i];

while(x[i]!=x[j])

{

if(j==0)break;

j=next[j];

}

if(x[i]==x[j])

next[i+1]=j+1;

else next[i+1]=0;

}

}

int KMP(char x[],char y[])

{//x是模式串,y是主串

int i,j;

int ans=0;

int m=strlen(x);

int n=strlen(y);

getnext(x);

j=0;

for(i=0;i<n;i++)

{

while(x[j]!=y[i])//如果发现失配了,j=next[j]的

//意思是找到j-1结尾的最长前缀等于最长后缀的下一个字符与y[i]比较,看相等与否

{

if(j==0)break;

j=next[j];

}

if(x[j]==y[i])j++;

if(j==m)

{

ans++;

j=next[j];

}

}

return ans;

}

int main()

{

int n;

char p[10005];

while(scanf("%d",&n)!=EOF)

{

while(n--)

{

scanf("%s%s",p,s);

getnext(p);

for(int i=0;i<=strlen(p);i++)

{

cout<<next[i]<<" ";

}

//printf("%d\n",KMP(p,s));

}

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: