KMP-Oulipo HDU - 1686
题目:
求模式串在待匹配串中的出现次数。
Input
第一行是一个数字T,表明测试数据组数。之后每组数据都有两行:
第一行为模式串,长度不大于10,000;
第二行为待匹配串,长度不大于1,000,000。(所有字符串只由大写字母组成)
Output
每组数据输出一行结果。
Sample Input
4
ABCD
ABCD
SOS
SOSOSOS
CDCDCDC
CDC
KMP
SOEASY
Sample Output
1
3
0
0
与 与 与《Number Sequence-HDU - 1711 》 相 似 , 需 要 母 与 每 一 个 位 置 匹 配 。 》相似,需要母与每一个位置匹配。 》相似,需要母与每一个位置匹配。
代码:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#include<unordered_map>
#define ll long long
#define inf 0x7fffffff
using namespace std;
const int N=1e6+10;
int T,n,m;
char s[N],p[N];
int Next[N];
void get_next()
{
for(int i=2,j=0;i<=m;i++)
{
while(j&&p[i]!=p[j+1]) j=Next[j];
if(p[i]==p[j+1]) j++;
Next[i]=j;
}
}
int main()
{
cin>>T;
while(T--)
{
scanf("%s%s",p+1,s+1);
n=strlen(s+1),m=strlen(p+1);
get_next();
int cnt=0;
for(int i=1,j=0;i<=n;i++)
{
while(j&&s[i]!=p[j+1]) j=Next[j];
if(s[i]==p[j+1]) j++;
if(j==m)
{
cnt++;
j=Next[j];
}
}
printf("%d\n",cnt);
}
return 0;
}