哎。。字符串排序后当做key 相同key的分成一个数组
func groupAnagrams(_ strs: [String]) -> [[String]] {
if strs.count == 1 {
let len = strs[0].count
if len == 0 || len == 1 {
return [strs]
}
}
var array = Array<[String]>()
var dict = Dictionary<String,Array<String>>()
for str in strs {
let tempStr = String(str.sorted())
if var tempArray = dict[tempStr] {
tempArray.append(str)
dict[tempStr] = tempArray
}else {
var insertArray = Array<String>()
insertArray.append(str)
dict[tempStr] = insertArray
}
}
for value in dict.values {
array.append(value)
}
return array
}
网友评论