为有牺牲多壮志,敢教日月换新天。

[Swift]LeetCode249.群组偏移字符串 $ Group Shifted Strings

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10214827.html 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

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

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

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

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:

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

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

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”。我们可以保持“移动”,这形成了一个序列:

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

给定只包含小写字母的字符串列表,将属于同一移位序列的所有字符串分组。

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

返回:

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

注意:对于返回值,每个内部列表的元素必须遵循字典顺序。


 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 }

 

posted @ 2019-01-03 16:14  为敢技术  阅读(216)  评论(0编辑  收藏  举报