题目传送门
思路:
首先,在字母表里面偶数位置的字符构成一个字符串s1,然后奇数位置构成一个字符串s2,这样每个字符串内部都是不相邻的了。然后将两个字符串合并时,要判断中间位置,有两种合并方法,s1+s2,s2+s1;如果这两种合并方法都不行则输出:No answer。
最后为什么是前两种不可以,就输出No answer(前面两种构造方法不行,则必然没有答案),这个可以证明。(有兴趣的可以自己证明一下,设s1的开始结尾字符为a1,b1,s2的开始结尾字符为a2,b2)
#include<bits/stdc++.h>
using namespace std;
#define pii pair<int, int>
#define mem(a,b) memset(a,b,sizeof(a))
#define per(i,a,b) for(int i=(a);i<=(b);i++)
#define rep(i,a,b) for(int i=(a);i>=(b);i--)
#define pi acos(-1.0)
#define inf 0x3f3f3f3f
#define Rand() (rand()|rand()<<15)
#define Srand() srand(time(0)^(unsigned)(unsigned long long)(new char))
typedef long long LL;
const double eps=1.0e-5;
const int maxn=200000+10;
const LL mod=1e9+7;
int n = 0,m = 0;
string s;
void solve(){
int num[30];
string s1,s2;
memset(num,0,sizeof(num));
int size = s.size();
per(i,0,size-1){
++num[s[i] - 'a'];
}
per(i,0,25){
if(i & 1){
while(num[i] > 0){
s1 += ('a' + i);
--num[i];
}
}else{
while(num[i] > 0){
s2 += ('a' + i);
--num[i];
}
}
}
if(abs(s1.back() - s2.front()) > 1){
cout << s1 + s2 << endl;
}else if(abs(s1.front() - s2.back()) > 1){
cout << s2 + s1 << endl;
}else{
cout << "No answer" << endl;
}
}
int main(){
std::ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int T = 0;
cin >> T;
while(T--){
cin >> s;
solve();
}
return 0;
}