题目描述
字符串哈希: 快速判断两个字符串是否相等
经验值: P=131, Q=2^64-1
变量: p[]: p[i]表示131的i次方
字符串哈希(步骤):
1. 先将原字符串的所有前缀的哈希求出 (h[i] = h[i - 1] * P + str[i])
2. 用对应的公式求出对应区间的哈希值是否一样—> 区间[l,r]中的哈希值为:h[r]-h[l-1]*p[r-l+1]
3. 每次都要对h数组取模(%Q)
样例
输入样例:
8 3
aabbaabb
1 3 5 7
1 3 6 8
1 2 1 2
输出样例:
Yes
No
Yes
算法1
(字符串哈希) $O(1)$
C++ 代码
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef unsigned long long ULL;
const int N = 100010, P = 131;
int n, m;
char str[N];
ULL h[N], p[N]; //p数组用来存储p的多少次方
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);
p[0] = 1;
for(int i = 1; i <= n; i ++ )
{
p[i] = p[i - 1] * P; //p[i]为P的i次方
h[i] = h[i - 1] * P + str[i]; //初始化h数组
}
while (m -- )
{
int l1, r1, l2, r2;
scanf("%d%d%d%d", &l1, &r1, &l2, &r2);
if(get(l1, r1) == get(l2, r2)) cout << "Yes" << endl;
else cout << "No" << endl;
}
return 0;
}