您的位置:首页 > 其它

KMP

2015-12-07 21:22 357 查看
KMP的核心就是next数组,next[j]存储的就是0~j-1的字符串前后缀最长长度.

老实说,这个部分真心难,我也只是大概弄懂,套套版,等放假要搞搞清楚。

poj3461

#include <stdio.h>
#include <string.h>
int next[1000100];
char p[1000100];
char s[1000100];
int l1;
int l2;
int ans;
void GetNext()
{
int i=0;
int j=-1;
next[0]=-1;
while(i<l1)
{
if ((j==-1)||(p[i]==p[j]))
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
void KMP()
{
int i=0;
int j=0;
while(i<l1&&j<l2)
{
if ((s[i]==p[j])||(j==-1))
{
i++;
j++;
}
else
j=next[j];
if (j==l2)//原来是一旦找到第一个符合,就退出循环
{
ans++;
j=next[j];
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%s%s",p,s);
l1=strlen(s);
l2=strlen(p);
ans=0;
GetNext();
KMP();
printf("%d\n",ans);
}
return 0;
}


poj2406最后有点....
#include <stdio.h>
#include <string.h>
char s[1000010];
int next[1000010];
int l;
int ls;
void GetNext()
{
int i,j;
i=0;
j=-1;
next[0]=-1;
while(i<ls)
{
if ((j==-1)||(s[i]==s[j]))
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}

}
int main()
{
while(scanf("%s",s)&&(s[0]!='.'))
{
ls=strlen(s);
GetNext();
l=ls-next[ls];
if ((l!=ls)&&(ls%l==0))
printf("%d\n",ls/l);
else
printf("1\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: