题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1686
题目描述:
给出两个串,分别为str1,str2,问str1在str2中出现了几次。
解题思路:
解决字符串匹配问题首选KMP。通过样例可以看出允许重复,自己运用next数组的
标准的KMP模板题,直接套用KMP模板即可。
但是:不要用cin,不知道为什么我用cin就TLE了。ORZ。
code
#include<bits/stdc++.h>
using namespace std;
const int MAXN=1e6+100;
const int MAXM=1e4+100;
char s1[MAXN],s2[MAXM];
int next1[MAXM];
void get_next1(int l)
{
int i,j;
i=0;j=next1[0]=-1;
while(i<l)
{
if(j==-1||s2[i]==s2[j])
{
i++;
j++;
next1[i]=j;
}
else
j=next1[j];
}
}
int kmp(int l1,int l2)
{
int i,j,ans=0;
i=j=0;
while(i<l1)
{
if(j==-1||s1[i]==s2[j])
{
i++;
j++;
}
else
j=next1[j];
if(j==l2)
{
ans++;
j=next1[j];
}
}
return ans;
}
int main()
{
int T,l1,l2;
scanf("%d",&T);
while(T--)
{
scanf("%s%s",s2,s1);
l1=strlen(s1);
l2=strlen(s2);
get_next1(l2);
printf("%d\n",kmp(l1,l2));
}
return 0;
}
本文为博主原创,未经允许不得转载。