【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())
相关推荐
张李浩几秒前
Leetcode 054螺旋矩阵 采用方向数组解决
算法·leetcode·矩阵
xixihaha132412 分钟前
将Python Web应用部署到服务器(Docker + Nginx)
jvm·数据库·python
big_rabbit050215 分钟前
[算法][力扣101]对称二叉树
数据结构·算法·leetcode
xixihaha132436 分钟前
Python游戏中的碰撞检测实现
jvm·数据库·python
ID_180079054731 小时前
模拟1688商品详情的Python API实现,返回符合风格的JSON数据
开发语言·python·json
程序员小远2 小时前
软件测试之功能测试详解
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
我的xiaodoujiao2 小时前
API接口自动化测试详细图文教程学习系列1--序章
python·学习·pytest
ZhengEnCi2 小时前
P1B-Python环境配置基础完全指南-Windows系统安装与验证
python
m0_716667072 小时前
NumPy入门:高性能科学计算的基础
jvm·数据库·python
带娃的IT创业者3 小时前
Weclaw 请求路由实战:一个 request_id 如何在 800 个并发连接中精准找到目标浏览器?
python·websocket·fastapi·架构设计·实时通信·openclaw·weclaw