题目描述:
给定一个字符串s,最多只能进行一次变换,返回变换后能得到的最小字符串(按照字典序进行比较)。变换规则:交换字符串中任意两个不同位置的字符。
输入描述:
—串小写字母组成的字符串s
输出描述:
按照要求进行变换得到的最小字符串
备注:
s是都是小写字符组成
1<=s.length<=1000
示例1
输入:
abcdef
输出:
abcdef
说明:
abcdef已经是最小字符串,不需要交换
示例2
输入∶
bcdefa
输出:
acdefb
说明:
a和b进行位置交换,可以得到最小字符串示例3
输入:
acdebf
输出:
abdecf
说明:
a的位置已经是最小了,就确定下一个位置c是不是最小,显而易见不是最小,最小是b,将c与b替换
java代码
package odTest;
import java.util.Arrays;
import java.util.Scanner;
public class minStr {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
char[] strList = scanner.nextLine().toCharArray();
int minIndex = 0;
int objectIndex = 0;
String[] objectStr = judgeMinStr(strList,minIndex,objectIndex).split(" ");
if(!objectStr[0].equals(objectStr[1])) {
char objectCharVa = strList[Integer.parseInt(objectStr[1])];
char minCharVa = strList[Integer.parseInt(objectStr[0])];
strList[Integer.parseInt(objectStr[1])] = minCharVa;
strList[Integer.parseInt(objectStr[0])] = objectCharVa;
}
System.out.println(String.valueOf(strList));
}
private static String judgeMinStr(char[] strList, int minIndex, int objectIndex) {
for(int i=objectIndex;i<strList.length;i++) {
if(strList[minIndex]>strList[i]) {
minIndex = i;
}
if(i==strList.length-1&&minIndex==objectIndex) {
return judgeMinStr(strList,minIndex+1,objectIndex+1);
}else if(i==strList.length-1){
return minIndex+" "+objectIndex;
}
}
return minIndex+" "+objectIndex;
}
}