更新:原来哈希被卡了,换了一份新的代码。
哈希模板。
容易发现,构造出来的字符串的形式为:两个 ,共享长度大于等于 的部分。
这个部分很容易发现是第一个 的后缀和第二个 的前缀,那么我们考虑枚举这个重叠部分的长度。设当前枚举的长度为 ,那么如果 ,这表明这个长度合法,取最大的 即可( 是 的最长 border),这个部分可以使用字符串哈希。
我们要注意,长度是 枚举的,因为一个字符串的 border 不能是它本身。
时间复杂度 。
代码如下:
#include <bits/stdc++.h>
#define int long long
const int N = 1e5 + 6;
using ull = int;
constexpr int P = 1e9 + 7;
void solve() {
std::string s;
std::cin >> s;
int n = (int)s.size();
s = " " + s;
std::vector<ull> pw(n + 1, 0), hsh(n + 1, 0);
pw[0] = 1;
for (int i = 1; i <= n; ++i) {
pw[i] = pw[i - 1] * 233 % P;
}
for (int i = 1; i <= n; ++i) {
hsh[i] = hsh[i - 1] * 233 + s[i] - 'a';
hsh[i] %= P;
}
auto get = [&](int l, int r) -> ull {
if (l > r) return 0;
return ((hsh[r] - hsh[l - 1] * pw[r - l + 1] % P) % P + P) % P;
};
for (int i = n - 1; i >= 0; --i) {
if (get(1, i) == get(n - i + 1, n)) {
std::vector<char> ans(2 * n - i + 1, 0);
for (int i = 1; i <= n; ++i) {
ans[i] = s[i];
}
for (int j = n - i + 1; j <= n - i + 1 + n - 1; ++j) {
ans[j] = s[j - (n - i + 1) + 1];
}
for (int j = 1; j <= 2 * n - i; ++j) {
std::cout << ans[j];
}
return;
}
}
}
int32_t main() {
std::ios::sync_with_stdio(0);
std::cin.tie(0), std::cout.tie(0);
int t;
// std::cin >> t;
t = 1;
while (t--) {
solve();
}
return 0;
}