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個字母中的任意一個移動到末尾,讓我們返回可以變換成的字母順序最小的字符串。剛開始看到的時候,博主感覺就是一個 BFS 遍歷,對於每一個狀態,都生成K個新的狀態,然后將沒有遍歷過的加入 queue 中去遍歷,然后維護一個全局最小的 res 即可,寫完之后拿到 OJ 中去測試了,結果跪了,Time Limit Exceeded!心想着,還能怎么優化呢?一逛論壇后發現,這道題還是真是有 trick 的,如果不仔細想,感覺不太容易想到。正確的思路其實是跟K值有關的,若 K=1,其實只有K中不同的情況,我們可以都生成,然后比較出其中最小的那個返回即可。關鍵是 K>1 的時候,比較 tricky,其實是可以轉換成有序的,即相當於直接對S串進行排序即可。我們就拿 S="53214", K=2 來舉例吧,轉換過程如下所示:
5 3 2 1 4
3 2 1 4 5
3 1 4 5 2
1 4 5 2 3
1 5 2 3 4
1 2 3 4 5
雖然不知道如何嚴格的證明當 K>1 時,一定能轉成有序的排序,但是博主試了幾個例子,都是可以的,論壇上說是一種類似於冒泡排序 Bubble Sort 的過程。若有哪位看官大神們知道如何證明,請務必留言告訴博主哈,參見代碼如下:
class Solution {
public:
string orderlyQueue(string S, int K) {
if (K > 1) {
sort(S.begin(), S.end());
return S;
}
string res = S;
for (int i = 0; i < S.size(); ++i) {
res = min(res, S.substr(i) + S.substr(0, i));
}
return res;
}
};
討論:微信公眾號粉絲 YF 童鞋提供了一種不嚴格的證明過程。只要證明 k=2 能將任意字符串轉為有序的,那么對於任意 k>1 的情況都是成立的。對於任意順序,我們都可以現將最小的數字移動到末尾,形成 xxxxx1 這種類型的,然后一定有辦法將第二小的數字移動到末尾,變成 xxxx12,以此類推類推,可以將所有數字按順序移動到末尾,形成類似冒泡排序的操作,拿 871524 來舉例:
- 將1移動到末尾
8 7 1 5 2 4
7 1 5 2 4 8
1 5 2 4 8 7
5 2 4 8 7 1
- 將2移動到末尾
5 2 4 8 7 1
5 4 8 7 1 2
- 將4移動到末尾
5 4 8 7 1 2
5 8 7 1 2 4
- 將5移動到末尾
5 8 7 1 2 4
8 7 1 2 4 5
- 將7移動到末尾
8 7 1 2 4 5
8 1 2 4 5 7
- 將8移動到末尾
8 1 2 4 5 7
1 2 4 5 7 8
Github 同步地址:
https://github.com/grandyang/leetcode/issues/899
參考資料:
https://leetcode.com/problems/orderly-queue/
https://leetcode.com/problems/orderly-queue/discuss/165862/Kgreater1-is-bubblesort
[LeetCode All in One 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)