描述
给定一个字符串s,最多只能进行一次变换,返回变换后能得到的最小字符串(按照字典序Q进行比较)。
变换规则:交换字符串中任意两个不同位置的字符。
输入描述
-串小写字母组成的字符串s;
输出描述
按照要求进行变换得到的最小字符串。
备注
s是都是小写字符组成,1≤s.length ≤ 1000。
用例:
输入:bcdefa
输出:acdefb
java实现
package com.des.data.test;
public class StringTransformationMinimumString {
public static void main(String[] args) {
String str = "bcdefa";
System.out.println(calculate(str));
}
public static String calculate(String str) {
String res = str;
char[] cArry = str.toCharArray();
for (int i = 0; i < cArry.length; i++) {
if (i == cArry.length - 1) {
break;
}
for (int j = i + 1; j < cArry.length; j++) {
char[] cArryN = str.toCharArray();
char tmp = cArryN[i];
cArryN[i] = cArryN[j];
cArryN[j] = tmp;
String strN = new String(cArryN);
if (res.compareTo(strN) > 0) {
res = strN;
}
}
}
return res;
}
}