题目来源:Extend to Palindrome - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
考虑添加字符后的回文串,可以发现其与原字符串重叠部分为回文串
因此问题可以转换为求原字符串的最长回文后缀
只需将manacher更新条件改为回文串至字符串末尾即可,复杂度O(N),本题也存在kmp做法
问题描述
“回文串”是一个正读和反读都一样的字符串,比如“level”或者“noon”等等就是回文串。给你一个字符串,问最少在字符串尾添加多少字符,可以使得字符串变为回文串。
输入格式
有多组测试数据。
每组测试数据第一行是一个正整数N,表示字符串长度,接下来一行是长度为N的字符串,字符串中只有小写字母。
N=0表示输入结束,并且不需要处理。
40%的数列元素个数N 1 ≤ N≤ 100;
30%的数列元素个数N 1 ≤ N≤ 1000;
20%的数列元素个数N 1 ≤ N≤ 10000;
10%的数列元素个数N 1 ≤ N≤ 100000;
输出格式
对于每组测试数据,输出一个非负整数:添加最少的字符数,可以使得字符串变为回文串。
样例输入
3 aba 4 aaac 0
样例输出
0 3
// clang-format off
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
#define add emplace_back
#define arr(...) vector<__VA_ARGS__>
#define arrin(a) for (auto& i : a) cin >> i
#define multi_test int i; cin >> i; while (i--)
// clang-format on
const int inf = INT_MAX / 2;
const int mod = 998244353;
const int mxn = 2e6 + 10;
int test_case = 1;
int manacher(string s, int n)
{
arr(int) v(n, 0);
int l = 0, r = -1, maxv = -1;
for (int i = 0; i < n; i++) {
int t = (i > r) ? 1 : min(v[l + r - i], r - i + 1);
while (i - t >= 0 and i + t < n and s[i - t] == s[i + t]) t++;
v[i] = t--;
if (i + v[i] >= n)
maxv = max(maxv, v[i]);
if (i + t > r)
l = i - t, r = i + t;
}
return maxv - 1;
}
void solve()
{
// cerr << "\ntest " << test_case++ << ":\n";
while (true) {
int n; cin >> n;
if (!n)
return;
string s, s_ = "|";
cin >> s;
for (char c : s)
s_ += c, s_ += '|';
cout << n - manacher(s_, s_.size()) << '\n';
}
}
// clang-format off
int main()
{
cin.tie(nullptr)->sync_with_stdio(false);
// multi_test
solve();
return 0;
}