★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(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 <= K <= S.length <= 1000
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 <= K <= S.length <= 1000
S
只由小写字母组成。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 }