【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())
相关推荐
Jac_kie_層樓1 分钟前
力扣hot100刷题记录(12.2)
算法·leetcode·职场和发展
Onebound_Ed4 分钟前
Python爬虫进阶:面向对象设计构建高可维护的1688商品数据采集系统
开发语言·爬虫·python
阿蔹28 分钟前
JavaWeb-Selenium 配置以及Selenim classnotfound问题解决
java·软件测试·python·selenium·测试工具·自动化
万粉变现经纪人1 小时前
如何解决 pip install 代理报错 407 Proxy Authentication Required 问题
windows·python·pycharm·beautifulsoup·bug·pandas·pip
李剑一1 小时前
Python学习笔记3
python
luod1 小时前
Python包
python
Mr Lee_2 小时前
Smali 文件生成dex装箱算法整合
开发语言·python·算法
电饭叔2 小时前
《python语言程序设计》2018版--第8章14题利用字符串输入作为一个信用卡号之一(Luhn算法解释)
android·java·python
希望有朝一日能如愿以偿2 小时前
力扣每日一题:统计梯形的数目
算法·leetcode·职场和发展
小女孩真可爱2 小时前
大模型学习记录(八)---------RAG评估
linux·人工智能·python