【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 天前
解决WSL环境下DeepSeek-OCR运行时内存不足问题
python·ocr·deepseek·deepseek-ocr
2501_941804321 天前
C++在高性能互联网服务开发与系统优化中的应用与实战经验解析
leetcode
FreeCode1 天前
LangGraph1.0智能体开发:Graph API概念与设计
python·langchain·agent
test管家1 天前
如何在Python中使用SQLite数据库进行增删改查操作?
python
希望有朝一日能如愿以偿1 天前
力扣每日一题:可被三整除的最大和
数据结构·算法·leetcode
无敌最俊朗@1 天前
力扣hot100-环形链表(2)142
算法·leetcode·链表
yangmf20401 天前
APM(三):监控 Python 服务链
大数据·运维·开发语言·python·elk·elasticsearch·搜索引擎
yangmf20401 天前
APM(二):监控 Python 服务
大数据·python·elasticsearch·搜索引擎
Elias不吃糖1 天前
LeetCode每日一练(189, 122)
c++·算法·leetcode
小猪咪piggy1 天前
【算法】day 19 leetcode 100 矩阵+贪心
算法·leetcode·矩阵