【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())
相关推荐
belldeep14 分钟前
python:genesis-world, Genesis-Embodied-AI
人工智能·python·ai·genesis
benchmark_cc1 小时前
A 股、港股、美股如何建立统一的标的主数据格式?
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
维克兜率天2 小时前
【维克】趋势型CTA:期货市场的“追涨杀跌“
人工智能·python
取名真是2 小时前
Python 算法知识点从基础到进阶
开发语言·python·算法
梦想不只是梦与想3 小时前
PyTorch、CPU、GPU、CUDA
人工智能·pytorch·python·深度学习·机器学习·cuda
数字融合3 小时前
透明化视频孪生危化安全管控解决方案
人工智能·python·安全
别问!问就是全会4 小时前
Jupyter Notebook 安装包下载|单元格分块运行,图表直接内嵌
ide·python·其他·jupyter
深蓝AI5 小时前
Python 缓存击穿实测:16 个并发请求如何只回源 1 次
python
benchmark_cc5 小时前
用 00700.HK 做港股行情清洗:字段核对、校验与个人量化开发实践
python·数据分析·pandas·量化交易·股票数据·quantdash
zh路西法5 小时前
【PACE】面向永磁同步电机PMSM 执行器的参数辨识与能耗感知强化学习 Sim-to-Real
python·cma-es·pmsm·sim-to-real·issac·pace