1. 程式人生 > >【LeetCode】899. Orderly Queue 解題報告(Python)

【LeetCode】899. Orderly Queue 解題報告(Python)

題目描述:

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.

題目大意

給了一個字串和一個數字K,每次操作可以把字串的前K個數字中任意抽取一個放到最後,可以做很多次操作。問,經過很多次操作之後,能構成的字母序最小的字串是什麼?

解題方法

這是一道智商題。

  1. K == 1的時候,沒有什麼好說的,每次只能把每個開頭的字母放到最後去,進行S.length次操作之後求字母序最小的字串。這個操作是把字串進行了旋轉。

     12345 -> 23451 -> 34512 -> 45123 -> 51234
    
  2. K > 1的時候,我們可以: 1). 把字串進行旋轉(相當於K == 1) 2). 把字串除了第一個字元的其餘部分進行旋轉

     012345 -> 023451 -> 034512 -> 045123 -> 051234
    

所以,我們可以使用步驟1裡面的操作,把整個字串最小的數字放到最前面去。然後對字串後面的部分再旋轉使後面部分最小的數字放到前面……以此類推,我們可以得到任何字串升序排列。

當k > 1的時候,這個過程相當於氣泡排序,所以,我們可以直接排序得到結果。

時間複雜度是O(N ^ 2),空間複雜度是O(N)。

class Solution(object):
    def orderlyQueue(self, S, K):
        """
        :type S: str
        :type K: int
        :rtype: str
        """
        if K == 1:
            res = S
            for i in range(len(S)):
                res = min(res, S[i:] + S[:i])
        else:
            res = "".join(sorted(list(S)))
        return res

參考資料:

日期

2018 年 10 月 4 日 —— 一個很不容易察覺的小錯誤,需要總結一下坑了!