【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())
相关推荐
SEO_juper22 分钟前
Node.js 重定向链检测工具:301 跳了几跳、有没有成环,一次看清
xml·开发语言·python·node.js·json·bash
曲径海盗28 分钟前
【Python 学习第 37 天】for 循环
python·学习笔记·编程入门
心静财富之门1 小时前
Python 数据共享四种方案完整实例(同进程 / JSON / Redis / HTTP)
数据库·python·oracle
王仔小奶1 小时前
慢SQL治理与性能调优:DBA如何用Shell/Python提升运维效率?
python·sql·dba
用户0332126663671 小时前
使用 Python 快速在 PowerPoint 中生成表格【教程】
python
夜晚回家2 小时前
Python 身份运算符详解 | is 与 == 到底差在哪
python
fengye2071612 小时前
cpython框架结构
python
用户91294046848422 小时前
大模型返回 JSON 后,先过这道 Python 校验
python
Dmz丶2 小时前
前端转 AI 100 天 Day 32:LLM 客户端工程化——重试、超时、降级、限流
python
曲径海盗2 小时前
【Python 学习第 39 天】for 循环
python·学习笔记·编程入门