字符串哈希实质上就是把每个不同的字符串转成不同的整数。
通过比较它们映射出的数字来代替比较字符串
字符串哈希_求子串
#include<iostream>
// 字符串求子串的哈希值
using namespace std;
typedef unsigned long long ull;//自然溢出
const int N=100010,P=131;//或者13331
int n,m;
char str[N];
ull h[N],p[N];
// 字符串 str [l,r] 哈希值 ,我们有很大概率认为 哈希值相等字符串相等
//如果想再次降低哈希冲突的概率,可以使用双哈希的方法
ull get(int l,int r)
{
return h[r]-h[l-1]*p[r-l+1];
}
int main()
{
scanf("%d%d%s",&n,&m,str+1);//字符串从1开始
p[0]=1;
for(int i=1;i<=n;i++)
{
p[i]=p[i-1]*P;
h[i]=h[i-1]*P+str[i];//P进制转换 这一行就是字符串哈希的核心内容
//ABSFE
//从A开始 A是最高位
}
/*
通过某种方式(P进制)把字符串变成数字
*/
while(m--)
{
int l1,r1,l2,r2;
cin>>l1>>r1>>l2>>r2;
if(get(l1,r1)==get(l2,r2)) cout<<"Yes";
else cout<<"No";
cout<<endl;
}
return 0;
}
字符串哈希_求母串
#include<bits/stdc++.h>
// 字符串求母串的哈希值
using namespace std;
typedef unsigned long long ull;
const int N=100010,P=131;//或者13331
int n;
char str[N];
ull h[N];//防止溢出
int main()
{
scanf("%s",str);//字符串从0开始
for(int i=0;str[i];i++) h[i]=h[i-1]*P+str[i];
//P进制转换 这一行就是字符串哈希的核心内容
//eg: ABSFE
//从A开始 A是最高位
cout<<h[strlen(str)-1]<<" "<<strlen(str);
return 0;
}