拉两次车,第一次假设最长回文串就在两边
第二次,先使得左右两边判回文,在将剩下的串 在manachar一遍,
比较两种情况取最大值,然后就是输出问题见代码
#include <bits/stdc++.h> using namespace std; const int maxn = 1e6 + 5; int pArr[maxn << 1], t; char s[maxn], chaArr[maxn << 1]; int manachar(int l, int r, int& flag) { int len = 0; chaArr[len++] = '$', chaArr[len++] = '#'; for (int i = l; i <= r; ++i) chaArr[len++] = s[i], chaArr[len++] = '#'; chaArr[len] = ' '; int R = -1, C = -1, ans = 0; for (int i = 0; i < len; ++i) { pArr[i] = R > i ? min(R - i, pArr[(C << 1) - i]) : 1; while (chaArr[i + pArr[i]] == chaArr[i - pArr[i]]) ++pArr[i]; if (pArr[i] + i > R) R = pArr[i] + i, C = i; if (pArr[i] + i > len - 2 && ans < pArr[i]) ans = pArr[i], flag = 0; if (i - pArr[i] < 2 && ans < pArr[i]) ans = pArr[i], flag = 1; } return ans - 1; } int main() { cin >> t; for (int i = 1; i <= t; ++i) { cin >> s + 1; int flag, len = strlen(s + 1); int ans = manachar(1, len, flag); int a = 1, b = len, flag2; while (a <= b && s[a] == s[b]) ++a, --b; if (a > b) { puts(s + 1); continue; } int res = manachar(a, b, flag2); if (ans >= (a - 1) * 2 + res) { if (flag) s[ans + 1] = ' ', cout << s + 1 << ' '; else cout << s + (len + 1 - ans) << ' '; continue; } if (flag2) s[a + res] = ' ', cout << s + 1 << s + (b + 1) << ' '; else s[a] = ' ', cout << s + 1 << s + (b + 1 - res) << ' '; } return 0; }