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

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

➤微信公众号:山青咏芝(shanqingyongzhi)

➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/

➤GitHub地址:https://github.com/strengthen/LeetCode

➤原文地址: https://www.cnblogs.com/strengthen/p/10607584.html

➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。

➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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 = 1
Output: 

Example 2:

Input: S = 3
Output:  

Note:

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

给出了一个由小写字母组成的字符串 S。然后,我们可以进行任意次数的移动

在每次移动中,我们选择前 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 }