I - Playing With Strings
注意分一下奇偶:
#include<bits/stdc++.h>
using namespace std;
int mmp[30];
int main()
{
int t;
cin>>t;
while(t--)
{
int sum=0;
memset(mmp,0,sizeof(mmp));
string str;
char ans[1005],cnt;
int m=0;
cin>>str;
int len=str.size();
for(int i=0; i<len; i++)
mmp[str[i]-'a'+1]++;
if(len%2==0)
{
for(int i=1; i<27; i++)
if(mmp[i]%2==1)
sum++;
if(sum>0)
cout<<"impossible";
else
{
for(int i=1; i<27; i++)
if(mmp[i]>0)
{
mmp[i]=mmp[i]/2;
while(mmp[i]--)
{
char temp=i-1+'a';
ans[m++]=temp;
cout<<temp;
}
}
}
for(int i=m-1; i>=0; i--)
cout<<ans[i];
}
else
{
for(int i=1; i<27; i++)
if(mmp[i]%2==1)
sum++;
if(sum!=1)
cout<<"impossible";
else
{
for(int i=1; i<27; i++)
if(mmp[i]>0)
{
if(mmp[i]%2==1)
{
cnt=i-1+'a';
mmp[i]--;
}
if(mmp[i]%2==0)
{
mmp[i]=mmp[i]/2;
while(mmp[i]--)
{
char temp=i-1+'a';
ans[m++]=temp;
cout<<temp;
}
}
}
cout<<cnt;
for(int i=m-1; i>=0; i--)
cout<<ans[i];
}
}
cout<<endl;
}
return 0;
}
本文介绍了一种构造回文串的方法,通过分析输入字符串中各字符出现的次数来判断是否能构造出回文串,并给出了详细的C++实现代码。算法区分了字符串长度为奇数和偶数两种情况。

被折叠的 条评论
为什么被折叠?



