在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an array of strings, group anagrams together. Example: Input:
Note:
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。 示例: 输入:
说明:
68ms 1 class Solution { 2 func hashValue(_ str: String) -> UInt64 { 3 var hash: UInt64 = 0 4 for code in str.unicodeScalars { 5 let value = code.value - 97 6 hash += UInt64(pow(5.0, Double(value))) 7 } 8 9 return hash 10 } 11 12 func groupAnagrams(_ strs: [String]) -> [[String]] { 13 var dic = [UInt64 : [String]]() 14 for str in strs { 15 let hash = hashValue(str) 16 if let strings = dic[hash] { 17 dic[hash] = strings + [str] 18 } else { 19 dic[hash] = [str] 20 } 21 } 22 return Array(dic.values) 23 } 24 } 124ms 1 class Solution { 2 func groupAnagrams(_ strs: [String]) -> [[String]] { 3 var result = [String : [String]]() 4 for item in strs { 5 let newStr = reformateString(item) 6 if let tempArray = result[newStr] { 7 var newArray = tempArray 8 newArray.append(item) 9 result[newStr] = newArray 10 } else { 11 result[newStr] = [item] 12 } 13 } 14 return [[String]](result.values) 15 } 16 17 func reformateString(_ str: String) -> String { 18 return String([Character](str).sorted(by: <)) 19 } 20 } 132ms 1 class Solution { 2 func groupAnagrams(_ strs: [String]) -> [[String]] { 3 var res = [[String]]() 4 var dict = [String: [String]]() 5 strs.forEach{(string) in 6 let charArray = Array(string).sorted(){$0 < $1} 7 let key = String(charArray) 8 if dict[key] != nil { 9 dict[key]?.append(string) 10 }else { 11 dict[key] = [string] 12 } 13 } 14 for key in dict.keys { 15 res.append(dict[key]!) 16 } 17 return res 18 } 19 } 140ms 1 class Solution { 2 func groupAnagrams(_ strs: [String]) -> [[String]] { 3 var map = [String: [String]]() 4 5 for str in strs { 6 let key = String(str.sorted()) 7 map[key, default: []].append(str) 8 } 9 10 return Array(map.values) 11 } 12 } 148ms 1 class Solution { 2 func groupAnagrams(_ strs: [String]) -> [[String]] { 3 var map: [String: [String]] = [:] 4 for str in strs { 5 let chars = str.sorted() 6 let key = String(chars) 7 if var list = map[key] { 8 list.append(str) 9 map[key] = list 10 } else { 11 map[key] = [str] 12 } 13 } 14 return Array(map.values) 15 } 16 } 316ms 1 class Solution { 2 func groupAnagrams(_ strs: [String]) -> [[String]] { 3 var groups = [String: [String]]() 4 for str in strs { 5 let strSorted = String(str.sorted()) 6 if groups[strSorted] == nil { 7 groups[strSorted] = [str] 8 } else { 9 groups[strSorted]?.append(str) 10 } 11 } 12 return groups.map { $1 } 13 } 14 }
|
请发表评论