Leetcode Hot 1001 分钟
8 次阅读

字母异位词分组

这里写一句文章摘要。

字母异位词分组 封面图

题目

image

[https://leetcode.cn/problems/group-anagrams/?envType=study-plan-v2&envId=top-100-liked]https://leetcode.cn/problems/group-anagrams/?envType=study-plan-v2&envId=top-100-liked

解法一

思路

通过哈希表来对字母异位词进行一个收集。 通过排序得到字符串的标准排序字符,然后以标准排序字符为key,以所有原本字符串的list为value。 最后通过python的list函数将字典转化为二维列表。

代码

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        mp = collections.defaultdict(list)
        for ch in strs:
            key = "".join(sorted(ch))
            mp[key].append(ch)
        return list(mp.values())

收获

  • 1 创建value为list的字典,用collections.defaultdict(list)
  • 2 字符串排序的方法,"".join(sored(ch))
  • 3 将字典的值转为二维列表的方法,list函数