-
Notifications
You must be signed in to change notification settings - Fork 8
/
1326D1_Prefix-SuffixPalindrome.cpp
83 lines (61 loc) · 1.39 KB
/
1326D1_Prefix-SuffixPalindrome.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
~ Author : @tridib_2003
~ Title : 1326D1. Prefix-Suffix Palindrome (Easy version)
~ Link : https://codeforces.com/contest/1326/problem/D1
*/
#include<bits/stdc++.h>
using namespace std;
int kmp(string s)
{
vector<int> lps(s.size(), 0);
for (int i = 1; i < (int)lps.size(); ++i)
{
int prev_idx = lps[i - 1];
while (prev_idx > 0 && s[i] != s[prev_idx])
{
prev_idx = lps[prev_idx - 1];
}
lps[i] = prev_idx + (s[i] == s[prev_idx] ? 1 : 0);
}
return lps[lps.size() - 1];
}
int largestPrefixPalindrome(string s) {
string t = s + '?';
reverse(s.begin(), s.end());
t += s;
return kmp(t);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int tc;
cin >> tc;
while (tc--) {
string s;
cin >> s;
int n = s.length();
int l = 0;
for (int i = 0, j = n - 1; i < j; ++i, --j) {
if (s[i] == s[j])
++l;
else
break;
}
string rem = s.substr(l, n - 2 * l);
string res = s.substr(0, l);
if (rem.size()) {
int len_pre = largestPrefixPalindrome(rem);
reverse(rem.begin(), rem.end());
int len_suf = largestPrefixPalindrome(rem);
if (len_pre > len_suf) {
reverse(rem.begin(), rem.end());
res += rem.substr(0, len_pre);
}
else
res += rem.substr(0, len_suf);
}
res += s.substr(n - l, l);
cout << res << '\n';
}
return 0;
}