A string S
of lowercase letters is given. Then, we may make any number of moves.html
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.git
Return the lexicographically smallest string we could have after any number of moves.github
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 来举例吧,转换过程以下所示:code
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 的过程。如有哪位看官大神们知道如何证实,请务必留言告诉博主哈,参见代码以下:htm
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 来举例:blog
8 7 1 5 2 4 7 1 5 2 4 8 1 5 2 4 8 7 5 2 4 8 7 1
5 2 4 8 7 1 5 4 8 7 1 2
5 4 8 7 1 2 5 8 7 1 2 4
5 8 7 1 2 4 8 7 1 2 4 5
8 7 1 2 4 5 8 1 2 4 5 7
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