Description
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the following conditions:
1.The length of t does not exceed the length of s.
2.t is a palindrome.
3.There exists two strings a and b (possibly empty), such that t=a+b ( “+” represents concatenation), and a is prefix of s while b is suffix of s.
Input
The input consists of multiple test cases. The first line contains a single integer t (1≤t≤105), the number of test cases. The next t lines each describe a test case.
Each test case is a non-empty string s, consisting of lowercase English letters.
It is guaranteed that the sum of lengths of strings over all test cases does not exceed 106.
Output
For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.
Example
input
5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba
output
a
abcdfdcba
xyzyx
c
abba
Solution
给你一个串s,让你求一个串t = a + b,其中a是s的前缀,b是s的后缀,满足t为回文串,且t的长度最长
看到回文串,我们自然会考虑到Manacher预处理出每个位置为中心的最长回文串长度
然后我们发现,最终的答案是由 前缀 + 回文子串 + 后缀 组成, 这里的前缀 + 后缀 一定要是回文
我们再预处理出前缀后缀最长回文的长度,最后枚举回文中心,判断能不能接上回文前后缀即可
Code
#include <bits/stdc++.h>
#define clr(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 8e6 + 5;
int p[maxn];
char s[maxn], Ma[maxn];
void init(int len){
for(int i = 0;i < len;++i){
p[i] = 0;
}
}
int Manacher(int len){
int l = 0;
init(len*4);
Ma[l++] = '$';Ma[l++] = '#';
for(int i = 0;i < len;++i){
Ma[l++] = s[i];Ma[l++] = '#';
}
Ma[l] = '@';
for(int i = 0;i < l;++i) p[i] = 0;
int id = 0, mx = 0;
for(int i = 0;i < l;++i){
p[i] = i < mx ? min(p[2*id-i],mx-i) : 1;
while(Ma[i+p[i]] == Ma[i-p[i]]) p[i]++;
if(i+p[i] > mx){
id = i; mx = i + p[i];
}
}
return l;
}
void solve(){
int n = strlen(s);
int l = Manacher(n);
int maxp = 0;
for(int i = 0;i < n;++i){
if(i > n / 2) break;
if(s[i] == s[n-i-1]) maxp++;
else break;
}
if(maxp * 2 + 1 >= n) {
printf("%s\n", s);return ;
}
int res = maxp * 2, pre = maxp - 1, suf = n - maxp;
for(int i = 1;i < l;++i){
if(p[i]-1>0){
int pred = (i - p[i]) / 2, midd = p[i] - 1, sufd = n - pred - midd;
int dis = min(pred,sufd);
if(dis > maxp) continue;
int tmp = dis * 2 + midd;
if(tmp > res){
res = tmp;
if(dis == pred) {pre = dis + midd - 1; suf = n - dis;}
if(dis == sufd) {pre = dis - 1; suf = n - dis - midd;}
}
}
}
for(int i = 0;i <= pre;++i) printf("%c", s[i]);
for(int i = suf;i < n;++i) printf("%c", s[i]);
printf("\n");
}
int main(){
int T;scanf("%d",&T);
while(T--){
scanf("%s",s);
solve();
}
return 0;
}