字符串匹配 哈希

#include<cstdio>
#include<cstdlib>
#include<cstring>

using namespace std;

#define ull unsigned long long

const ull base=12306;
const ull rd=rand()%10;

ull h[100010],bit[100010];

char s1[100010],s2[100010];

ull get(int l,int r)
{
	return h[r]-h[l-1]*bit[r-l+1];
}

int main()
{
	scanf("%s%s",s1+1,s2+1);
	int l1=strlen(s1+1),l2=strlen(s2+1);
	ull h2=0;
	for (int a=1;a<=l2;a++)
		h2=h2*base+s2[a]+rd;

	bit[0]=1;//bit[i]=base^i
	for (int a=1;a<=l1;a++)
	{
		bit[a]=bit[a-1]*base;
		h[a]=h[a-1]*base+s1[a]+rd;//h[a]代表s1[1]~s1[a]的hash值 前缀hash值
	}

	int cnt=0;
	for (int a=1;a+l2-1<=l1;a++)
	{
		//看s1[a]~s1[a+l2-1]
		//和s2是否一样
		if (get(a,a+l2-1) == h2) cnt++;
	}
	printf("%d\n",cnt);


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值