#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;
}
字符串匹配 哈希
最新推荐文章于 2024-08-15 22:41:27 发布