題目
給定一個字符串s,最多隻能進行一次變換,返回變換後能得到的最小字符串(按照字典序進行比較)。 變換規則:交換字符串中任意兩個不同位置的字符。
輸入描述:
一串小寫字母組成的字符串s
輸出描述:
按照要求進行變換得到的最小字符串
示例
輸入:abcdef
輸出:abcdef
說明:abcdef已經是最小字符串,不需要交換
輸入:bcdefa
輸出:acdefb
說明:a和b進行位置交換,可以得到最小字符串
備註:
s是都是小寫字符組成
1<=s.length<=1000
思路
貪心策略
- 根本不需要每個都窮舉出來進行比對
- 對於一個字符串,只需要把字符串中最小字符調換位置到第一位就是最小字符串
- 如果第一個字符已經是最小字符,則對除去第一個字符的字串進行操作
所以我就直接用遞歸進行操作
注意
如果最小字符有多個,記得取最後一個最小字符,不然會有很多用例通不過
代碼
import java.util.Scanner;
public class Main1 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String inputString = in.next();
char[] chars = inputString.toCharArray();
moveTheSmallest2Head(chars, 0);
System.out.println(new String(chars));
}
private static void moveTheSmallest2Head(char[] chars, int start) {
if (start == chars.length - 1) {
return;
}
boolean headIsSmallest = true;
char smallest = chars[start];
int samallestIndex = start;
for (int i = start + 1; i < chars.length; i++) {
if (chars[i] < chars[start] && chars[i] <= smallest) {
headIsSmallest = false;
smallest = chars[i];
samallestIndex = i;
}
}
if (headIsSmallest) {
moveTheSmallest2Head(chars, start + 1);
} else {
char temp = chars[start];
chars[start] = chars[samallestIndex];
chars[samallestIndex] = temp;
}
}
}