【Golang】LeetCode 49. 字母异位词分组

49. 字母异位词分组

题目描述

思路

我们同样使用哈希表来解决这道问题。

具体来说,我们对初始给定的strs数组进行遍历,对于每一个取到的字符串str,我们将其转为[]byte并使用sort.Slice进行排序。

我们将排序好的[]byte命名为curr,它就代表着当前字符串的一种"模式",对于字典序相同的"模式",它们应该被归纳为同一组异位词,因为构成它们的字符经过字典序排序之后是相同的。

在遍历之前我们应该建立一个map,它的key是string类型,value是[]string类型。curr作为key,我们更新它的value,通过append的方式将当前的str加入到value的数组当中。

在遍历结束之后,我们对字典的value进行一次遍历,将答案放到数组当中。

Golang 题解

go 复制代码
func groupAnagrams(strs []string) [][]string {
    ans := [][]string{}
    mp := map[string][]string{}
    for _, str := range strs {
        curr := []byte(str)
        sort.Slice(curr, func(i, j int) bool {
            return curr[i] > curr[j] 
        })

        if _, ok := mp[string(curr)]; !ok {
            mp[string(curr)] = []string{}
        }
        mp[string(curr)] = append(mp[string(curr)], str)
    }

    for _, v := range mp {
        ans = append(ans, v)
    }

    return ans
}
相关推荐
alphaTao7 小时前
LeetCode 每日一题 2026/10/12-2026/10/18
算法·leetcode
Cccp.1237 小时前
【leetcode】(十三)大数据处理
数据结构·算法·leetcode
Pniubi8 小时前
力扣70爬楼梯
数据结构·算法·leetcode
Navigator_Z1 天前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2081 天前
leetcode 64最小路径和
算法·leetcode·职场和发展
Nil2081 天前
leetcode 72编辑距离
算法·leetcode·职场和发展
Nil2081 天前
leetcode 136只出现一次的数字
leetcode·哈希算法·散列表
局部有解1 天前
LeetCode Hot100 438 找到字符串中所有字母异位词
c++·算法·leetcode
Nil2081 天前
leetcode 75颜色分类
数据结构·算法·leetcode
aqiu1111111 天前
CodeTop按顺序刷题0003:LeetCode 206. 反转链表(迭代法图文详解与动态演示)
算法·leetcode·链表