[Swift]LeetCode899. 有序隊列 | Orderly Queue

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-vytdfozr-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

A string S of lowercase letters is given.  Then, we may make any number of moves.git

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.github

Return the lexicographically smallest string we could have after any number of moves. 微信

Example 1:spa

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:code

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:htm

  1. 1 <= K <= S.length <= 1000
  2. S consists of lowercase letters only.

給出了一個由小寫字母組成的字符串 S。而後,咱們能夠進行任意次數的移動blog

在每次移動中,咱們選擇前 K 個字母中的一個(從左側開始),將其從原位置移除,並放置在字符串的末尾。索引

返回咱們在任意次數的移動以後能夠擁有的按字典順序排列的最小字符串。 隊列

示例 1:

輸入:S = "cba", K = 1
輸出:"acb"
解釋:
在第一步中,咱們將第一個字符(「c」)移動到最後,得到字符串 「bac」。
在第二步中,咱們將第一個字符(「b」)移動到最後,得到最終結果 「acb」。

示例 2:

輸入:S = "baaca", K = 3
輸出:"aaabc"
解釋:
在第一步中,咱們將第一個字符(「b」)移動到最後,得到字符串 「aacab」。
在第二步中,咱們將第三個字符(「c」)移動到最後,得到最終結果 「aaabc」。 

提示:

  1. 1 <= K <= S.length <= 1000
  2. S 只由小寫字母組成。

Runtime: 40 ms
Memory Usage: 19.7 MB
 1 class Solution {
 2     func orderlyQueue(_ S: String, _ K: Int) -> String {
 3         if K > 1
 4         {
 5             var arrS:[Character] = Array(S)
 6             arrS.sort()
 7             return String(arrS)
 8         }
 9         var res:String = S
10         for i in 1..<S.count
11         {
12             var tmp:String = S.subString(i) + S.subString(0, i);
13             if res > tmp {res = tmp}
14         }
15         return res
16     }
17 }
18 
19 extension String {
20     // 截取字符串:從index到結束處
21     // - Parameter index: 開始索引
22     // - Returns: 子字符串
23     func subString(_ index: Int) -> String {
24         let theIndex = self.index(self.endIndex, offsetBy: index - self.count)
25         return String(self[theIndex..<endIndex])
26     }
27 
28     // 截取字符串:指定索引和字符數
29     // - begin: 開始截取處索引
30     // - count: 截取的字符數量
31     func subString(_ begin:Int,_ count:Int) -> String {
32         let start = self.index(self.startIndex, offsetBy: max(0, begin))
33         let end = self.index(self.startIndex, offsetBy:  min(self.count, begin + count))
34         return String(self[start..<end]) 
35     }
36 }
相關文章
相關標籤/搜索