HDU 1686 Oulipo (KMP模板题)
题目链接:
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;
}
本文为博主原创,未经允许不得转载。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步