# 899. Orderly Queue

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. `1 <= K <= S.length <= 1000`
2. `S` consists of lowercase letters only.

``````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
``````

``````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;
}
};
``````

• 将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

https://leetcode.com/problems/orderly-queue/discuss/165878/C%2B%2BJavaPython-Sort-String-or-Rotate-String

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation