[Leetcode]字母异位词分组

[Leetcode]字母异位词分组

Leetcode-字母异位词分组

题目描述

给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。

示例:
输入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]
输出:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]

说明:
所有输入均为小写字母。
不考虑答案输出的顺序。

解题思路
  • 当且仅当它们的排序字符串相等时,两个字符串是字母异位词。
  • 维护一个映射,在 Java 中,我们将键存储为字符串,例如,code。 在 Python 中,我们将键存储为散列化元组,例如,(‘c’, ‘o’, ‘d’, ‘e’)。
    在这里插入图片描述
实现代码
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        res = {}
        for s in strs:
            res[tuple(sorted(s))] = res.get(tuple(sorted(s)), []) + [s]
        return list(res.values())