两段子串的哈希相等吗
用 unsigned long long 做前缀哈希:h[i+1] = h[i] × B + 字母序号(a 记 1),不取模,让它自然溢出。
运行下面这段程序:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
typedef unsigned long long ull;
const ull B = 131;
int main() {
string s = "abcabc";
int n = s.size();
vector<ull> h(n + 1, 0), pw(n + 1, 1);
for (int i = 0; i < n; i++) {
h[i + 1] = h[i] * B + (ull)(s[i] - 'a' + 1);
pw[i + 1] = pw[i] * B;
}
auto get = [&](int l, int r) { return h[r] - h[l] * pw[r - l]; };
cout << (get(0, 3) == get(3, 6)) << "/" << (get(0, 3) == get(1, 4)) << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论