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

1 问题

给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。

字母异位词 是由重新排列源单词的所有字母得到的一个新单词。

示例 1:

输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]

输出: [["bat"],["nat","tan"],["ate","eat","tea"]]

示例 2:

输入: strs = [""]

输出: [[""]]

示例 3:

输入: strs = ["a"]

输出: [["a"]]

2 答案

这题直接不会

官方解,使用字典记录,其中字典的键,必须是不可变类型,所以用tuple。

python 复制代码
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        dict = {}
        for s in strs:
            key = tuple(sorted(s))  # 字典的键用tuple
            dict[key] = dict.get(key,[]) + [s]  # get(key,[]) get 不到则返回[]
        return list(dict.values())
相关推荐
努力学算法的蒟蒻1 小时前
day84(2.12)——leetcode面试经典150
算法·leetcode·面试
程序员酥皮蛋1 小时前
hot 100 第二十三题 23.反转链表
数据结构·算法·leetcode·链表
小鸡吃米…1 小时前
TensorFlow - TensorBoard 可视化
python·tensorflow·neo4j
TracyCoder1231 小时前
LeetCode Hot100(51/100)——155. 最小栈
数据结构·算法·leetcode
Y.O.U..1 小时前
力扣刷题-86.分隔链表
算法·leetcode·链表
OPEN-Source1 小时前
给 Agent 安装技能:工具抽象、自动选工具与安全边界
人工智能·python·agent·rag·deepseek
TracyCoder1232 小时前
LeetCode Hot100(52/100)——394. 字符串解码
算法·leetcode·职场和发展
ljxp12345682 小时前
高效删除链表重复节点
python
thginWalker2 小时前
leetcode有空可以挑战的题目
leetcode
52Hz1182 小时前
力扣207.课程表、208.实现Trie(前缀树)
python·leetcode