求模式串在待匹配串的出现次数。
Input
第一行是一个数字T,表明测试数据组数。 之后每组数据都有两行:第一行为模式串,长度不大于10000;第二行为待匹配串,长度不大于1000000。所有字符串只由大写字母组成。
Output
每组数据输出一行结果。
Sample Input
4 ABCD ABCD ABA ABABABA CDCDCDC CDC KMP NAIVE
Sample Output
1 3 0 0
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
typedef unsigned long long ll;
const int base = 27;//
const int maxn = 1e6+10;
char a[maxn],b[maxn];
ll p[maxn];
ll has[maxn];
int main()
{
int T,i;
cin>>T;
p[0]=1;
for(i=1; i<maxn; i++)
p[i]=p[i-1]*base;
while(T--)
{
memset(a+1,0,sizeof(a+1));
memset(b+1,0,sizeof(b+1));
scanf("%s",a+1);
scanf("%s",b+1);
int l1 = strlen(a+1);
int l2 = strlen(b+1);
ll h=0;
for(i=1; i<=l1; i++)
{
h=h*base+a[i];
}
for(i=1; i<=l2; i++)
{
has[i]=has[i-1]*base+b[i];
}
int ans=0;
for(i=1; i<=l2-l1+1; i++)
{
if(h==has[i+l1-1]-has[i-1]*p[l1])
ans++;
}
printf("%d\n",ans);
}
return 0;
}