#include<bits/stdc++.h>
using namespace std;
const int N=1e6+5;
char p[N],s[N];//
typedef unsigned long long ull;//
const ull base=131;//
ull h1[N],h2[N],b[N];
ull getHash(ull h[],int l,int r) //
{
return h[r]-h[l-1]*b[r-l+1];
}
int main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
cin>>p+1;int m=strlen(p+1);//p+1表示匹配时从下标1开始
cin>>s+1;int n=strlen(s+1);
b[0]=1;//
for(int i=1;i<=n;i++)
{
b[i]=b[i-1]*base;//
h1[i]=h1[i-1]*base+(int)p[i];
h2[i]=h2[i-1]*base+(int)s[i];
}
int ans=0;
for(int i=1;i+m-1<=n;i++)
{//
if(getHash(h1,1,m)==getHash(h2,i,i+m-1))ans++;
}
cout<<ans<<'\n';
return 0;
}
字符串Hash 斤斤计较的小Z
于 2025-02-03 14:32:15 首次发布