【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())
相关推荐
Eric.Lee202121 小时前
ubuntu 安装 Miniconda
linux·运维·python·ubuntu·miniconda
无心水21 小时前
【Python实战进阶】1、Python高手养成指南:四阶段突破法从入门到架构师
开发语言·python·django·matplotlib·gil·python实战进阶·python工程化实战进阶
李剑一21 小时前
Python学习笔记1
python
sin_hielo21 小时前
leetcode 2435
数据结构·算法·leetcode
Salt_07281 天前
DAY 19 数组的常见操作和形状
人工智能·python·机器学习
无心水1 天前
【Python实战进阶】2、Jupyter Notebook终极指南:为什么说不会Jupyter就等于不会Python?
python·jupyter·信息可视化·binder·google colab·python实战进阶·python工程化实战进阶
稚辉君.MCA_P8_Java1 天前
Gemini永久会员 Java动态规划
java·数据结构·leetcode·排序算法·动态规划
小白程序员成长日记1 天前
2025.11.23 力扣每日一题
算法·leetcode·职场和发展
上班日常摸鱼1 天前
Shell脚本基础教程:变量、条件判断、循环、函数实战(附案例)
python
无心水1 天前
【Python实战进阶】5、Python字符串终极指南:从基础到高性能处理的完整秘籍
开发语言·网络·python·字符串·unicode·python实战进阶·python工业化实战进阶