2025-06-07 22:55:54
发布于:广东
给你们先看看我的代码
#include <bits/stdc++.h>
using namespace std;
// Liu 独家代码,抄袭必废
string solve(string s) {
sort(s.begin(), s.end());
int n = s.size();
if (s[0] == s[n-1]) {
return s;
}
int cnt[26] = {0};
for (char c : s) {
cnt[c-'a']++;
}
for (int i = 0; i < 26; ++i) {
if (cnt[i] == 1) {
string res;
res += char('a'+i);
for (int j = 0; j < 26; ++j) {
if (j != i) {
res += string(cnt[j], char('a'+j));
}
}
return res;
}
}
if (cnt[s[0]-'a'] * 2 - 1 <= n) {
string res;
res += s[0];
cnt[s[0]-'a']--;
for (int i = 1; i < 26; ++i) {
while (cnt[i] > 0) {
res += char('a'+i);
cnt[i]--;
if (cnt[s[0]-'a'] > 0) {
res += s[0];
cnt[s[0]-'a']--;
}
}
}
return res;
} else {
string res;
res += s[0];
cnt[s[0]-'a']--;
int second = -1;
for (int i = 1; i < 26; ++i) {
if (cnt[i] > 0) {
second = i;
break;
}
}
res += char('a'+second);
cnt[second]--;
while (cnt[s[0]-'a'] > 0) {
res += s[0];
cnt[s[0]-'a']--;
}
for (int i = second+1; i < 26; ++i) {
if (cnt[i] > 0) {
res += char('a'+i);
cnt[i]--;
break;
}
}
for (int i = 0; i < 26; ++i) {
res += string(cnt[i], char('a'+i));
}
return res;
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
cout << solve(s) << '\n';
}
return 0;
}
全部评论 1
到CF去交
1周前 来自 广东
0
有帮助,赞一个