KMP模板
2016-10-25 14:40
183 查看
O(n+m)时间复杂读的kmp
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
char a[1005],b[1005];
int next[1005];
void getnext(int bl) //next数组
{ next[0]=-1;
int i=0,j=-1;
while(i<bl)
{if(j==-1||b[i]==b[j])
{
i++;j++;
if(b[i]==b[j])
next[i]=next[j];
else
next[i]=j;
}
else j=next[j];
}
}
int kmp(int kal,int kbl) //判断
{ getnext(kbl);
int i=0,j=0;
while(i<kal)
{
if(j==-1||a[i]==b[j])
{
i++;j++;
}
else j=next[j];
if(j==kbl)
return 1;
}
return 0;
}
int main()
{ int n,k=0;
scanf("%d",&n);
cin.get();
while(n--)
{ k++;
scanf("%s%s",a,b);
int ans=kmp(strlen(a),strlen(b));
if(ans==1)printf("Case #%d: Yes\n",k);
else printf("Case #%d: No\n",k);
}
return 0;
}
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
char a[1005],b[1005];
int next[1005];
void getnext(int bl) //next数组
{ next[0]=-1;
int i=0,j=-1;
while(i<bl)
{if(j==-1||b[i]==b[j])
{
i++;j++;
if(b[i]==b[j])
next[i]=next[j];
else
next[i]=j;
}
else j=next[j];
}
}
int kmp(int kal,int kbl) //判断
{ getnext(kbl);
int i=0,j=0;
while(i<kal)
{
if(j==-1||a[i]==b[j])
{
i++;j++;
}
else j=next[j];
if(j==kbl)
return 1;
}
return 0;
}
int main()
{ int n,k=0;
scanf("%d",&n);
cin.get();
while(n--)
{ k++;
scanf("%s%s",a,b);
int ans=kmp(strlen(a),strlen(b));
if(ans==1)printf("Case #%d: Yes\n",k);
else printf("Case #%d: No\n",k);
}
return 0;
}
相关文章推荐
- 扩展kmp 模板
- KMP模板
- 洛谷P3375 【模板】KMP字符串匹配
- 无聊贴个KMP模板
- POJ 3461 Oulipo [KMP模板题]
- 扩展KMP模板
- KMP 模板
- 模板 KMP
- KMP 算法模板
- 模板 kmp字符串匹配
- HDU 1711 Number Sequence(KMP模板)
- 洛谷 P3375 【模板】KMP字符串匹配
- P3375【模板】KMP字符串匹配
- HDU 1711 Number Sequence(KMP模板)
- KMP小模板
- 【HDU6153 2017中国大学生程序设计竞赛 - 网络选拔赛 D】【KMP 或 扩展KMP】A Secret 匹配串前缀中含有的模板串前缀长度和
- KMP 模板
- POJ 3461 Oulipo【KMP】【模板题】(找出第一个字符串在第二个字符串中出现次数)
- POJ3461 Oulipo KMP模板
- HDU 1711 Number Sequence (KMP模板)