字符串哈希

字符串哈希,将字符串映射成为哈希值,从而达到快速比较求得子串的功能。
模板,注意(字符串从1开始存储):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
typedef unsigned long long ULL;
ULL h[N], p[N]; // h[k]存储字符串前k个字母的哈希值, p[k]存储 P^k mod 2^64
// 初始化
p[0] = 1;
for (int i = 1; i <= n; i ++ )
{
h[i] = h[i - 1] * P + str[i];
p[i] = p[i - 1] * P;
}

// 计算子串 str[l ~ r] 的哈希值
ULL get(int l, int r)
{
return h[r] - h[l - 1] * p[r - l + 1];
}

例题(模板题):
https://www.acwing.com/problem/content/submission/843/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10,P=131;
typedef unsigned long long ull;
ull h[N],p[N];
string s;
ull get(int l,int r)
{
return h[r]-h[l-1]*p[r-l+1];
}
int main(void)
{
int n,m;
scanf("%d%d",&n,&m);
cin>>s;
s = "0"+s;
p[0] =1;
for(int i=1;i<=n;i++)
{
p[i] = p[i-1]*P;
h[i] = h[i-1]*P +s[i];
}
int l1,r1,l2,r2;
while(m--)
{
scanf("%d%d%d%d",&l1,&r1,&l2,&r2);
if(get(l1,r1)==get(l2,r2))
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}


}

字符串哈希
http://jty-123.github.io/2022/04/26/字符串哈希/
作者
Jty
发布于
2022年4月26日
许可协议