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

49. 字母异位词分组

题目描述

思路

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

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

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

在遍历之前我们应该建立一个map,它的keystring类型,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
}
相关推荐
wabs6661 天前
关于字符串【力扣541.反转字符串II的思考】
数据结构·算法·leetcode·字符串
土司大王1 天前
LeetCode hot100——移动零
java·算法·leetcode
旖旎夜光1 天前
LeetCode 30:串联所有单词的子串(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口
Nil2081 天前
leetcode 48旋转图像
算法·leetcode·职场和发展
Nil2081 天前
leetcode 206反转链表
算法·leetcode·链表
想吃火锅10052 天前
【leetcode】200. 岛屿数量
算法·leetcode·职场和发展
Nil2082 天前
leetcode 54螺旋矩阵
算法·leetcode·矩阵
evans在进步2 天前
LeetCode 394:字符串解码——Java 单栈模拟与嵌套解析详解
java·python·leetcode
Nil2082 天前
leetcode 189轮转数组
数据结构·算法·leetcode
吃着火锅x唱着歌2 天前
LeetCode 3885.设计事件管理器
算法·leetcode·职场和发展