解法一:排序法
异位词排序后的结果字符一定是相同的
func groupAnagrams(strs []string) [][]string {
res := make([][]string, 0)
if len(strs) == 0{
return res
}
sortedStrMap := make(map[string][]string) // sortedStr: {rawStr...}
for _, s := range strs {
// 对字符串按字典序排序,转为byte数组处理
tmp := []byte(s)
sort.Slice(tmp, func(i, j int) bool{
return tmp[i] < tmp[j]
})
// 排序结果转为string类型, 追加进map里
sortedStr := string(tmp)
sortedStrMap[sortedStr] = append(sortedStrMap[sortedStr], s)
}
// 转换结果
for _, ans := range sortedStrMap{
res = append(res, ans)
}
return res
}
解法二:计数法
按每个单词的出现次数作为标识,对所有异位词进行分组
func groupAnagrams(strs []string) [][]string {
res := make([][]string, 0)
if len(strs) == 0{
return res
}
letterCountMap := make(map[[26]int][]string) // array: {str}
for _, s := range strs{
cnt := [26]int{}
for _, c := range s{
cnt[c - 'a']++
}
letterCountMap[cnt] = append(letterCountMap[cnt], s)
}
for _, ans := range letterCountMap{
res = append(res, ans)
}
return res
}