P2957 [USACO09OCT] Barn Echoes G - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)https://www.luogu.com.cn/problem/P2957
题目分析
对于求单个字符串的哈希值相当于求前缀和,而求单个字符串的子串的哈希值则相当于求其区间和;
那么只需求两个字符串的前缀哈希值;再枚举两个字符串的重复部分的长度即可求解;
代码示例
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
const int N = 1e5 + 10;
const int base = 131;
ull p[N], h1[N], h2[N];
char a[N], b[N];
void init(ull h[], char s[], int lenth) {
p[0] = 1, h[0] = 0;
for(int i = 1; i <= lenth; i++) {
p[i] = p[i - 1] * base;
h[i] = h[i - 1] * base + s[i];
}
}
ull get(ull h[], int l, int r) {
return h[r] - h[l - 1] * p[r - l + 1];
}
int main() {
scanf("%s%s", a + 1, b + 1);
int len1 = strlen(a + 1), len2 = strlen(b + 1);
int minl = min(len1, len2);
init(h1, a, len1); init(h2, b, len2);
int ans = -1;
int al, bl;
for(int i = 1; i <= minl; i++) {
al = get(h1, 1, i) == get(h2, len2 - i + 1, len2) ? i : -1;
bl = get(h1, len1 - i + 1,len1) == get(h2, 1, i) ? i : -1;
ans = max(ans, max(al, bl));
}
cout << ans <<' ';
return 0;
}