49.M 字母异位词分组
Problem: 49. 字母异位词分组
思路
分组其实就是做group by操作,因此需要决定一个key。对于异味词,它们排序后的结果一定是相同的。因此,以排序后的字符串作为key。
Code
func groupAnagrams(strs []string) [][]string {
group := map[string][]string{}
for _, str := range strs {
key := format(str)
group[key] = append(group[key], str)
}
res := make([][]string, 0, len(group))
for _, v := range group {
res = append(res, v)
}
return res
}
func format(str string) string {
bytes := []byte(str)
sort.Slice(bytes, func(i, j int) bool { return bytes[i] < bytes[j] })
return string(bytes)
}
Last updated
Was this helpful?