代码拉取完成,页面将自动刷新
/*
* @lc app=leetcode.cn id=49 lang=golang
*
* [49] 字母异位词分组
*/
// 3. hash
// @lc code=start
func groupAnagrams(strs []string) [][]string {
mp := map[[26]int][]string{}
for _, str := range strs {
cnt := [26]int{}
for _, b := range str {
cnt[b-'a']++
}
mp[cnt] = append(mp[cnt], str)
}
ans := make([][]string, 0, len(mp))
for _, v := range mp {
ans = append(ans, v)
}
return ans
}
// @lc code=end
// 2. hash
// @lc code=start
func groupAnagrams(strs []string) [][]string {
mp := map[string][]string{}
for _, str := range strs {
s := []byte(str)
sort.Slice(s, func(i, j int) bool { return s[i] < s[j] })
sortedStr := string(s)
mp[sortedStr] = append(mp[sortedStr], str)
}
ans := make([][]string, 0, len(mp))
for _, v := range mp {
ans = append(ans, v)
}
return ans
}
// @lc code=end
// 1. 暴力超时
// @lc code=start
func groupAnagrams(strs []string) (ans [][]string) {
for i := 0; i < len(strs); i++ {
temp := []string{strs[i]}
for j := i + 1; j < len(strs); j++ {
if isAnagram(strs[i], strs[j]) {
temp = append(temp, strs[j])
strs = append(strs[:j], strs[j+1:]...)
j--
}
}
ans = append(ans, temp)
}
return
}
func isAnagram(s string, t string) bool {
s1, s2 := []byte(s), []byte(t)
sort.Slice(s1, func(i, j int) bool { return s1[i] < s1[j] })
sort.Slice(s2, func(i, j int) bool { return s2[i] < s2[j] })
return string(s1) == string(s2)
}
// @lc code=end
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。