在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a string, we can "shift" each of its letter to its successive letter, for example: "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","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","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 }
|
请发表评论