求模式串在待匹配串的出现次数。

求模式串在待匹配串的出现次数。

Input

第一行是一个数字T,表明测试数据组数。
之后每组数据都有两行:第一行为模式串,长度不大于10000;第二行为待匹配串,长度不大于1000000。所有字符串只由大写字母组成。

Output

每组数据输出一行结果。

Sample Input

4
ABCD
ABCD
ABA
ABABABA
CDCDCDC
CDC
KMP
NAIVE

Sample Output

1
3
0
0

    这也是一道hash的算法题, 下面给出AC代码:

#include<stdio.h>
#include<string.h>
#define ull unsigned long long
char ch1[1000009];
ull hash[1000009];
char ch2[10009];
const int p=300;
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        memset(hash,0,sizeof(hash));
        ull hp=1,hp1=0,hp2=0;
        scanf("%s %s",ch2,ch1);
        int l2=strlen(ch2);
        int l1=strlen(ch1);
        for(int i=0;i<l2;i++)
            hp*=p;
        for(int i=0;i<l2;i++)
            hp1=hp1*p+ch2[i];
        hash[0]=ch1[0];
        for(int i=1;i<l1;i++)
            hash[i]=hash[i-1]*p+ch1[i];
        int cnt=0;
        if(hash[l2-1]==hp1) cnt++;
        for(int i=l2;i<l1;i++)
        {
            ull m=hash[i]-hash[i-l2]*hp;
            if(m==hp1) cnt++;
        }
        printf("%d\n",cnt);
    }
    return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值