回文串就两种情况,一种是有一个奇数个的字母,另一种是没有的。所以我们需要统计出题目给出的字母是否为奇数个,且奇数个只能有一个,如果超过一个就不能构成回文串了。
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
string makehuiwen(string s)
{
vector<int>count(26, 0);//初始化26个字母的个数
for (auto it : s)//且数组是根据字典序排的所以遍历就直接是升序
{
count[it - 'A']++;
}//统计26个字母各有多少个
int odd = 0;//奇数个的字母个数
char onlyone = '\0';//奇数的那个,也就是中间那个字母
for (int i = 0; i < 26; i++)
{
if (count[i] % 2 != 0)
{
odd++;
onlyone='A'+i;
}
if (odd > 1)return "No Solution";
}
string left;//构造左边
for (int i = 0; i < 26; i++)
{
for (int j = 0; j < count[i] / 2; j++)//左边有一半的字母
{
left += 'A' + i;
}
}
string right = left;
reverse(right.begin(), right.end());
if (odd == 1)
{
return left + onlyone + right;
}
else
{
return left + right;
}
}
int main()
{
string s;
cin >> s;
string ans = makehuiwen(s);
cout << ans << endl;
return 0;
}