Skip to main content

49. Group Anagrams

分析

原有单词中任意顺序进行组合,可以相互形成,就可以构成一组
具有上述性质的字符集,排序后一定一样

本题要注意的和 Go 语言的一些语言特性有关

Another instance of helpful zero values is a map of slices. Appending to a nil slice just allocates a new slice, so it’s a one-liner to append a value to a map of slices; there’s no need to check if the key exists.

题解

function groupAnagrams(strs: string[]): string[][] {
const memo: Record<string, string[]> = {}

for (const str of strs) {
const key = str.split("").sort().join("")

if (!memo[key]) {
memo[key] = []
}
memo[key].push(str)
}

return Object.values(memo)
};
func groupAnagrams(strs []string) [][]string {
memo := make(map[string][]string)

for _, str := range strs {
sortedStr := getSortedStr(str)
memo[sortedStr] = append(memo[sortedStr], str)
}

ans := [][]string{}
for _, strArray := range memo {
ans = append(ans, strArray)
}

return ans
}

func getSortedStr(str string) string {
bytes := []byte(str)
sort.Slice(bytes, func(i int, j int) bool { return bytes[i] < bytes[j] })
return string(bytes)
}