leetcode 49. 字母异位词分组

题解

遍历strs数组,对word进行排序,判断str是否在hashMap

示例代码(go)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func groupAnagrams(strs []string) [][]string {
res := make([][]string, 0)
hashMap := make(map[string]int)
for _, word := range strs {
arr := strings.Split(word, "")
sort.Strings(arr)
str := strings.Join(arr, "")
if i, ok := hashMap[str]; ok {
res[i] = append(res[i], word)
} else {
hashMap[str] = len(res)
res = append(res, []string{word})
}
}
return res
}