Gym - 101102F F. Exchange

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”.

Input

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.

Output

For each test case, print the required string on a single line.

Example

题意:可以对字符串进行一个操作,把2个字母互换(这2个字母是不同的),一旦互换必须把所有x换成y,所有y换成x,最多可以进行一次这样的操作,求字典序最小的字符串。

Input

3
hamza
racecar
mca

Output

ahmzh
arcecra
acm
#include<iostream>
#include<stdio.h>
#include<queue>
#include<string.h>
#include<math.h>
using namespace std;
char s[100050];
int main()
{
    int t,i;
    cin>>t;
    while(t--)
    {
        scanf("%s",s);
        int len=strlen(s);
        int c[26];
        memset(c,0,sizeof(c));
        for(i=0; i<len; i++)
        {
            c[s[i]-'a']++;
        }
        char a,b;
        int k=0,j;
        for(i=0; i<26; i++)
        {
            if(c[i])
            {
                a='a'+i;
                if(a<s[k])
                {
                    b=s[k];
                    break;
                }
                else if(a==s[k])
                {
                    j=k;
                    while(s[j]>=s[k])
                        k++;
                }
            }
        }
        if(i==26)
        {
            printf("%s\n",s);
            continue;
        }
        for(i=0; i<len; i++)
        {
            if(s[i]==a)
            s[i]=b;
            else if(s[i]==b)
            s[i]=a;
        }
        printf("%s\n",s);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41374539/article/details/81609296
今日推荐