原题链接
题目描述
A string S of lowercase letters is given. Then, we may make any number of moves.
In each move, we choose one of the first K letters (starting from the left), remove it, and place it at the end of the string.
Return the lexicographically smallest string we could have after any number of moves.
Example 1:
Input: S = "cba", K = 1
Output: "acb"
Explanation:
In the first move, we move the 1st character ("c") to the end, obtaining the string "bac".
In the second move, we move the 1st character ("b") to the end, obtaining the final result "acb".
Example 2:
Input: S = "baaca", K = 3
Output: "aaabc"
Explanation:
In the first move, we move the 1st character ("b") to the end, obtaining the string "aacab".
In the second move, we move the 3rd character ("c") to the end, obtaining the final result "aaabc".
Note:
1 <= K <= S.length <= 1000
S consists of lowercase letters only.
这个题目的关键是要想清楚,当K>1的时候,相当于任意两个相邻的数都能交换,任意两个相邻的数都能交换,可以类比到冒泡排序,这是冒泡排序的主要思想。
下边证明:
假设数组中任意两个相邻的数c[i] = a, 和c[j] = b(j = i + 1),我们的目标是将其交换:下面是变幻的过程:
XXXab***
| (将第一个移到最后,循环3次)
ab***XXX
| (将第二个移到最后)
a***XXXb
| (将第一个移到最后)
***XXXba
| (将第一个移到最后,循环3次)
XXXba***
成功!
说明我们已经能将任意两个相邻的数进行交换,因此,我们可以用冒泡排序,也就是能直接对其进行排序。
代码:
class Solution {
public String orderlyQueue(String S, int K) {
if(K == 0 || S == null) {
return S;
}
if(K == 1) {
int len = S.length();
String res = new String(S);
for(int i = 0; i < len; i++) {
S = S.substring(1) + S.charAt(0);
if(S.compareTo(res) < 0) {
res = S;
}
}
return res;
}else {
char[] temp = S.toCharArray();
Arrays.sort(temp);
return String.valueOf(temp);
}
}
}