★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-hxicknsq-mb.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Return the lexicographically smallest subsequence of text
that contains all the distinct characters of text
exactly once. git
Example 1:github
Input: "cdadabcc"
Output: "adbc"
Example 2:微信
Input: "abcd"
Output: "abcd"
Example 3:app
Input: "ecbacba"
Output: "eacb"
Example 4:post
Input: "leetcode"
Output: "letcod"
Note:spa
1 <= text.length <= 1000
text
consists of lowercase English letters.返回字符串 text
中按字典序排列最小的子序列,該子序列包含 text
中全部不一樣字符一次。 code
示例 1:htm
輸入:"cdadabcc" 輸出:"adbc"
示例 2:blog
輸入:"abcd" 輸出:"abcd"
示例 3:
輸入:"ecbacba" 輸出:"eacb"
示例 4:
輸入:"leetcode" 輸出:"letcod"
提示:
1 <= text.length <= 1000
text
由小寫英文字母組成1 class Solution { 2 3 func smallestSubsequence(_ text: String) -> String { 4 var cnt = [Int](repeating: 0, count: 26) , used = cnt 5 var idx = 0, dic = [Character: Int](), chars = Array(text) 6 _ = "abcdefghijklmnopqrstuvwxyz".map { dic[$0] = idx; idx += 1 } 7 for ch in chars { 8 let idx = dic[ch]! 9 let ct = cnt[idx] 10 cnt[idx] = ct + 1 11 } 12 13 var ans = "" 14 for ch in chars { 15 let idx = dic[ch]! 16 let ct = cnt[idx] 17 cnt[idx] = ct - 1 18 19 let uct = used[idx] 20 used[idx] = uct + 1 21 if uct > 0 { continue } 22 while !ans.isEmpty && ans.last! > ch && cnt[dic[ans.last!]!] > 0 { 23 used[dic[ans.last!]!] = 0 24 ans.removeLast() 25 } 26 ans += "\(ch)" 27 } 28 return ans 29 } 30 }
Runtime: 16 ms
1 class Solution { 2 func smallestSubsequence(_ text: String) -> String { 3 var cnt:[Int] = [Int](repeating:0,count:26) 4 var used:[Int] = [Int](repeating:0,count:26) 5 var res:[Character] = [Character]() 6 let arrText:[Character] = Array(text) 7 let arrIndex:[Int] = Array(text).map{$0.ascii - 97} 8 for i in arrIndex 9 { 10 cnt[i] += 1 11 } 12 for (index,i) in arrIndex.enumerated() 13 { 14 cnt[i] -= 1 15 if used[i]++ > 0 {continue} 16 while(!res.isEmpty && (res.last!.ascii - 97) > i && cnt[res.last!.ascii - 97] > 0) 17 { 18 used[res.last!.ascii - 97] = 0 19 res.popLast() 20 } 21 res.append(arrText[index]) 22 } 23 return String(res) 24 } 25 } 26 27 //Character擴展 28 extension Character 29 { 30 //Character轉ASCII整數值(定義小寫爲整數值) 31 var ascii: Int { 32 get { 33 return Int(self.unicodeScalars.first?.value ?? 0) 34 } 35 } 36 } 37 38 /*擴展Int類,實現自增++、自減--運算符*/ 39 extension Int{ 40 //後綴++:先執行表達式後再自增 41 static postfix func ++(num:inout Int) -> Int { 42 //輸入輸出參數num 43 let temp = num 44 //num加1 45 num += 1 46 //返回加1前的數值 47 return temp 48 } 49 }