Palindrome Reorder
题目描述
Given a string, your task is to reorder its letters in such a way that it becomes a palindrome (i.e., it reads the same forwards and backwards).
输入
The only input line has a string of length n() consisting of characters A–Z.
输出
Print a palindrome consisting of the characters of the original string. You may print any valid solution. If there are no solutions, print "NO SOLUTION".
样例输入
AAAACACBA
样例输出
AACABACAA
AC代码
#include<bits/stdc++.h>
#define ll long long
using namespace std;
string s;
ll len,cnt[26],odd_count,total;
int main(){ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);cin>>s;len=s.size();total=len;string ans="";char mid='\0';for(ll i=0;i<len;i++){cnt[s[i]-'A']++;}for(int i=0;i<26;i++){if(cnt[i]%2){odd_count++;total-=cnt[i];}}if(odd_count>1){cout<<"NO SOLUTION\n";return 0;}else{ans.reserve(total/2);for(int i=0;i<26;i++){ans.append(cnt[i]/2,'A'+i);if(cnt[i]%2){mid='A'+i;}}string str=ans;reverse(str.begin(),str.end());if(odd_count){cout<<ans<<mid<<str<<"\n";}else{cout<<ans<<str<<"\n";}}return 0;
}
WA代码(为甚么啊)
#include<bits/stdc++.h>
#define ll long long
using namespace std;
string s;
ll len,cnt[26],odd_count,total;
int main(){ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);cin>>s;len=s.size();total=len;string ans="",mid="";for(ll i=0;i<len;i++){cnt[s[i]-'A']++;}for(int i=0;i<26;i++){if(cnt[i]%2){odd_count++;total-=cnt[i];}}if(odd_count>1){cout<<"NO SOLUTION\n";return 0;}else{ans.reserve(total/2);for(int i=0;i<26;i++){if(cnt[i]&&cnt[i]%2==0){ans.append(cnt[i]/2,'A'+i);}else if(cnt[i]%2){mid.reserve(cnt[i]);mid.append(cnt[i],'A'+i);}}ans[ans.size()]='\0';mid[mid.size()]='\0';string str=ans;str[str.size()]='\0';reverse(str.begin(),str.end());if(odd_count){cout<<ans<<mid<<str<<"\n";}else{cout<<ans<<str<<"\n";}}return 0;
}