题解:CF1326D1 Prefix-Suffix Palindrome (Easy version)
写在前面
本来板刷
思路
本题实质上是求解一个字符串
-
- 只由
a 组成,且a 回文。 - 只由
b 组成,且b 回文。
于是解法就很明朗了,首先找出原字符串
AC 代码
#include <bits/stdc++.h>
using namespace std;
bool check (const string& s) {
int n = s.size();
for (int i = 0; i < n / 2; i++) {
if (s[i] != s[n - i - 1]) return false;
}
return true;
}
void F1ower() {
string s;
cin >> s;
int n = s.size();
string t = s;
reverse(t.begin(), t.end());
int ini = 0;
string res;
for (int i = 0; i < n; i++) {
if (s[i] != t[i]) break;
ini++;
res += s[i];
}
string plus;
string temp;
for (int i = ini; i < n - ini; i++) {
temp += s[i];
if (check(temp) && temp.size() > plus.size()) {
plus = temp;
}
}
string temp2;
for (int i = n - ini - 1; i >= ini; i--) {
temp2 += s[i];
if (check(temp2) && temp2.size() > plus.size()) {
plus = temp2;
}
}
string ans = res + plus;
for (int i = n - ini; i < n; i++) ans += s[i];
cout << (ans.size() > n ? s : ans) << "\n";
}
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t = 1;
cin >> t;
while(t--) {
F1ower();
}
return 0;
}