[Swift]LeetCode249.羣組偏移字符串 $ Group Shifted Strings

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

Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence:git

"abc" -> "bcd" -> ... -> "xyz"

Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.github

For example, given: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"]
Return:數組

[
  ["abc","bcd","xyz"],
  ["az","ba"],
  ["acef"],
  ["a","z"]
]

Note: For the return value, each inner list's elements must follow the lexicographic order.微信


給定一個字符串,咱們能夠將它的每一個字母「移位」到它的連續字母,例如:「abc」->「bcd」。咱們能夠保持「移動」,這造成了一個序列:app

"abc" -> "bcd" -> ... -> "xyz"

給定只包含小寫字母的字符串列表,將屬於同一移位序列的全部字符串分組。函數

例如,給定:["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"]spa

返回:code

[
  ["abc","bcd","xyz"],
  ["az","ba"],
  ["acef"],
  ["a","z"]
]

注意:對於返回值,每一個內部列表的元素必須遵循字典順序。orm


 1 class Solution {
 2     func groupStrings(_ strings:[String]) -> [[String]] {
 3         var res:[[String]] = [[String]]()
 4         var m:[String:Set<String>] = [String:Set<String>]()
 5         for a in strings
 6         {
 7             var t:String = ""
 8             for c in a.characters
 9             {
10                 t += String((c.ascii + 26 - a[0].ascii) % 26) + ","
11             }
12             if m[t] == nil
13             {
14               m[t] = Set<String>()
15             }
16              m[t]!.insert(a) 
17         }
18         for it in m.values
19         {
20             res.append(Array(it))
21         }
22         return res
23     }
24 }
25 
26 extension Character  
27 {  
28   //屬性:ASCII整數值(定義小寫爲整數值)
29    var ascii: Int {
30         get {
31             let s = String(self).unicodeScalars
32             return Int(s[s.startIndex].value)
33         }
34     }
35 }
36 
37 extension String {        
38     //subscript函數能夠檢索數組中的值
39     //直接按照索引方式截取指定索引的字符
40     subscript (_ i: Int) -> Character {
41         //讀取字符
42         get {return self[index(startIndex, offsetBy: i)]}
43     }
44 }
相關文章
相關標籤/搜索