题意:
有n个长度为m的字符串, 把它们拼接在一起, 输出可能的最长回文串。
思路:
用map记录字符串的个数,使用reverse函数得到它翻转之后的字符串,如果有反转后的字符串,就把它在最前拼面和最后面拼接上。 用string的‘+’运算进行拼接。如果是单独的一个字符串,但是它是回文的,就把已经得到的字符串分成两半,还是要用string的'+"运算,因为确定长度的string访问下标会出错。
#pragma warning(disable:4996)
#include<iostream>
#include<cstring>
#include<cstdio>
#include<set>
#include<string>
#include<cmath>
#include<algorithm>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
int n, m;
map<string, int>mp;
bool ispali(string x) {
int i = 0, j = m - 1;
while (i <= j) {
if (x[i] != x[j])return 0;
i++; j--;
}
return 1;
}
int main()
{
int i;
string s[105], ans, t;
string t1, t2;
scanf("%d%d", &n, &m);
for (i = 0; i < n; i++)
{
cin >> s[i];
mp[s[i]]++;
}
for (i = 0; i < n; i++) {
if (mp[s[i]]) {
t = s[i];
reverse(t.begin(), t.end());
if (s[i] == t && mp[s[i]] < 2)continue;
if (mp[t])
{
ans = s[i] + ans + t;
mp[s[i]]--;
mp[t]--;
}
}
}
for (i = 0; i < n; i++) {
if (ispali(s[i]))
{
int L = ans.length();
for (int j = 0; j < L / 2; j++)
{
t1 += ans[j];
}
for (int j = L / 2; j < L; j++)
t2 += ans[j];
ans = t1 + s[i] + t2;
break;
}
}
printf("%d\n", ans.length());
cout << ans << endl;
return 0;
}