题目描述:
You are given a string s, consisting of lowercase Latin letters. Every letter appears in it no more than twice.
Your task is to rearrange the letters in the string in such a way that for each pair of letters that appear exactly twice, the distance between the letters in the pair is the same. You are not allowed to add or remove letters.
It can be shown that the answer always exists. If there are multiple answers, print any of them.
大意:
给您一个由小写拉丁字母组成的字符串s。每个字母出现在其中不超过两次。
您的任务是重新排列字符串中的字母,使每对恰好出现两次的字母之间的距离相同。不允许添加或删除字母。
可以看出,答案总是存在的。如果有多个答案,请打印其中任何一个。
输入格式:
The first line contains a single integer1≤t≤10^3— the number of testcases.
Each testcase consists of a non-empty string s, consisting of lowercase Latin letters. Every letter appears in the string no more than twice. The length of the string doesn't exceed 52.
第一行包含单个整数1≤t≤10^3-测试用例的数量。
每个测试用例都包含一个非空字符串s,由小写拉丁字母组成。每个字母在字符串中出现不超过两次。字符串的长度不超过52。
输出格式:
For each testcase, print a single string. Every letter should appear in it the same number of times as it appears in string s. For each pair of letters that appear exactly twice, the distance between the letters in the pair should be the same.
If there are multiple answers, print any of them.
对于每个测试用例,打印一个字符串。每个字母在其中出现的次数应与在字符串s中出现的次数相同。对于每对恰好出现两次的字母,这对字母之间的距离应该相同。
如果有多个答案,请打印其中任何一个。
输入输出样例
输入 #1
3
oelhl
abcdcba
ac
输出 #1
hello
ababcdc
ac
思路:
找出出现2次的字母,先对这些字母进行处理,再输出只出现一次的字母
代码:
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
char a[52]={};
scanf("%s",a);
int l=strlen(a);
int b[26]={};//记录字母出现次数
for(int i=0;i<l;i++){
b[a[i]-'a']++;
}
//对出现两次的字母的处理
int t1=2;
while(t1--){
for(int i=0;i<26;i++){
if(b[i]==2){
printf("%c",i+'a');
}
}
}
//对出现一次的字母的处理
for(int i=0;i<26;i++){
if(b[i]==1){
printf("%c",i+'a');
}
}
cout<<endl;
}
return 0;
}