【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())
相关推荐
yang_coder3 分钟前
juypter notebook启动ssl报错的处理记录
python·jupyter
江华森40 分钟前
exp01_Python_数据类型
开发语言·python
大鱼>1 小时前
模型可解释性:特征重要性/SHAP/LIME
人工智能·python·机器学习·lstm
代码不接地1 小时前
【时间序列预测】0.时间序列任务知识地图
python·ai编程
许彰午2 小时前
77_Python数据清洗实战技巧
开发语言·python
Sam09272 小时前
【AI 算法精讲 16】BPE 分词:从字节对到子词
人工智能·python·算法·ai
江华森2 小时前
04-python-面向对象
开发语言·python
梦帮科技2 小时前
基于EVM架构的Web3音频确权与RNS Token智能合约设计深度解析
人工智能·python·架构·web3·区块链·音视频·智能合约
AI行业学习2 小时前
Notepad++ 官方纯净下载+完整安装教程(Windows)【2026.7.5】
开发语言·windows·python·前端框架·html·notepad++