字符串的hash匹配

时间:2025-04-27 22:03:50

  如果要比较字符串是否相等,首先想到的是KMP算法,但是hash更加简洁易于编写,hash的目的是把一串字符转化成一个数字,用数字来比较是否相等。我让mod=912837417 Base=127,防止hash碰撞

 #include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL mod=;
const LL Base=;
char T[],P[];
LL lenT,lenP;
LL hash[];
LL base[];
LL hashP;
inline LL query(LL l,LL r){
LL ans=(hash[r]-(hash[l-]*base[r-l+]))%mod;
if(ans<) ans+=mod;
return ans;
}
int main(){
scanf("%s%s",T+,P+);
lenT=strlen(T+); lenP=strlen(P+);
base[]=;
for(int i=;i<=lenT;i++){
base[i]=(base[i-]*Base)%mod;
hash[i]=(hash[i-]*Base+(LL)(T[i]-'a'+))%mod;
if(i<=lenP) hashP=(hashP*Base+(LL)(P[i]-'a'+))%mod;
}
for(int i=;i<=lenT-lenP+;i++){
LL now=query(i,i+lenP-);
if(now==hashP){
cout<<"从第"<<i<<"位开始匹配"<<endl;
return ;
}
}
cout<<"不能匹配"<<endl;
return ;
}