1 Star 0 Fork 0

HanYong/leetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
49.字母异位词分组.go 1.42 KB
一键复制 编辑 原始数据 按行查看 历史
HanYong 提交于 2023-05-22 14:50 +08:00 . tree
/*
* @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
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yinhu000/leetcode.git
git@gitee.com:yinhu000/leetcode.git
yinhu000
leetcode
leetcode
master

搜索帮助

371d5123 14472233 46e8bd33 14472233