Given a string of lowercase English letters. You are allowed to choose two letters that exist in any position in the string, replace all occurrences of the first letter you chose with the second one, and replace all occurrences of the second letter you chose with the first one.
Your task is to find the string that comes first in dictionary order among all possible strings that you can get by performing the above operation at most once.
For example, by exchanging letter ‘a’ with letter ‘h’ in string “hamza”, we can get string “ahmzh”.
The first line of input contains a single integer T, the number of test cases.
Each test case contains a non-empty string on a single line that contains no more than 105 lowercase English letters.
For each test case, print the required string on a single line.
3 hamza racecar mca
ahmzh arcecra acm
Source
2016 ACM Amman Collegiate Programming Contest
My Solution
题意:可以对字符串进行一个操作,把2个字母互换(这2个字母是不同的),一旦互换必须把所有x换成y,所有y换成x,最多可以进行一次这样的操作,求字典序最小的字符串。
贪心、简单题
用cnt[i]表示字母出现的次数,用flag[i]表示之前j字母是否出现过,
对于每个字母x,则在1~x-1里找之前没有出现过但在整个字符串出现过的字母进行互换,找出后退出循环,之后进行互换
复杂度 O(26*n)
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
using namespace std;
typedef long long LL;
const int maxn = 1e5 + 8;
string s;
int cnt[26];//, cur[maxn][6];
bool flag[26];
int main()
{
#ifdef LOCAL
freopen("e.txt", "r", stdin);
//freopen("e.out", "w", stdout);
#endif // LOCAL
ios::sync_with_stdio(false); cin.tie(0);
int T, sz, a, b, i, j;
cin >> T;
while(T--){
memset(cnt, 0, sizeof cnt);
//memset(cur, 0, sizeof cur);
memset(flag, false, sizeof flag);
a = b = -1;
cin >> s;
sz = s.size();
for(i = 0; i < sz; i++){
cnt[s[i] - 'a']++;
}
for(i = 0; i < sz; i++){
flag[s[i] - 'a'] = true;
if(a != -1) break;
if(s[i] - 'a' == 0) continue;
else{
for(j = 0; j < s[i] - 'a'; j++){
if(cnt[j] != 0 && !flag[j]){
a = s[i] - 'a', b = j;
break;
}
}
}
}
if(a == -1) cout << s << endl;
else{
for(i = 0; i < sz; i++){
if(s[i] - 'a' == a){
s[i] = 'a' + b;
}
else if(s[i] - 'a' == b){
s[i] = 'a' + a;
}
}
cout << s << endl;
}
}
return 0;
}
Thank you!
------from ProLights