题目
给定一个字符串s,最多只能进行一次变换,返回变换后能得到的最小字符串(按照字典序进行比较) 。
变换规则:交换字符串中任意两个不同位置的字符。
输入描述:
一串小写字母组成的字符串s
输出描述:
按照要求进行变换得到的最小字符串
备注:
s 是都是小写字符组成
1<=
1<= s.length
<=1000
<=1000
示例1
输入:
abcdef
输出:
abcdef
说明:
abcdef已经是最小字符串,不需要交换
示例2
输入:
bcdefa
输出:
acdefb
说明:
a 和 b 进行位置交换,可以得到最小字符串
参考代码
package RealTest;
/**
* @ClassName MinStringAfterSwap
* @Description TODO
* @Author 21916
* @Date 2024/3/18 14:19
*/
public class MinStringAfterSwap {
public static String minString(String s) {
char[] chars = s.toCharArray();
int n = chars.length;
// 遍历字符串中的每个字符
for (int i = 0; i < n - 1; i++) {
char currentChar = chars[i];
int minIndex = i; // 记录从当前位置开始的最小字符的索引
// 寻找从当前位置开始的最小字符及其索引
for (int j = i + 1; j < n; j++) {
if (chars[j] < currentChar) {
currentChar = chars[j];
minIndex = j;
}
}
// 如果找到比当前字符更小的字符,则交换它们
if (minIndex != i) {
char temp = chars[i];
chars[i] = chars[minIndex];
chars[minIndex] = temp;
// 因为已经找到了更优解并进行了交换,无需继续检查后面的字符
break;
}
}
// 将字符数组转换回字符串并返回
return new String(chars);
}
public static void main(String[] args) {
String s1 = "abcdef";
System.out.println(minString(s1)); // 输出: abcdef
String s2 = "bcdefa";
System.out.println(minString(s2)); // 输出: acdefb
}
}