【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())
相关推荐
ZTLJQ8 小时前
序列化的艺术:Python JSON处理完全解析
开发语言·python·json
H5css�海秀8 小时前
今天是自学大模型的第一天(sanjose)
后端·python·node.js·php
阿贵---8 小时前
使用XGBoost赢得Kaggle比赛
jvm·数据库·python
无敌昊哥战神8 小时前
【LeetCode 257】二叉树的所有路径(回溯法/深度优先遍历)- Python/C/C++详细题解
c语言·c++·python·leetcode·深度优先
x_xbx9 小时前
LeetCode:148. 排序链表
算法·leetcode·链表
李昊哲小课10 小时前
第1章-PySide6 基础认知与环境配置
python·pyqt·pyside
2401_8942419211 小时前
用Pygame开发你的第一个小游戏
jvm·数据库·python
木井巳11 小时前
【递归算法】子集
java·算法·leetcode·决策树·深度优先
lightqjx11 小时前
【算法】二分算法
c++·算法·leetcode·二分算法·二分模板
Zzzz_my12 小时前
正则表达式(RE)
pytorch·python·正则表达式