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;
}
#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;
}
相关文章推荐
- Mac上Android studio环境搭建
- P-Called-Party-ID头域
- 2015年7月15日 JS第一课(JS,声明变量,数据类型)
- mouseenter和mouseleave,mouseover和mouseout
- Objective-C设计模式——桥接Bridge(接口适配)
- 使用ConnectivityManager监听网络状态变化
- URAL 1021 Sacrament of the Sum
- ARM Linux 3.x的设备树(Device Tree)
- 析构函数什么情况下要定义为虚函数?
- 相似图片搜索的原理
- HDU5297莫比乌斯函数,容斥原理从1到n中数字中去掉形如a^r的数字
- 已知两种遍历序列求原始二叉树
- 第四篇 学习OpenCV之访问图像数据
- Android Scroller简单用法
- 第四篇 学习OpenCV之访问图像数据
- [转]学习C#:Attribute与Property
- HDU5298立体几何
- 孪生素数问题
- HDOJ 1095 A+B for Input-Output Practice (VII)(水题)
- HDU 5294 Tricks Device (最大流+最短路)