【LeetCode】字母异位词分组

目录


一、题目

给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。

字母异位词 是由重新排列源单词的所有字母得到的一个新单词。

示例 1:

输入: strs = "eat", "tea", "tan", "ate", "nat", "bat"

输出: \["bat","nat","tan","ate","eat","tea"]

示例 2:

输入: strs = ""

输出: \[""]

示例 3:

输入: strs = "a"

输出: \["a"]

提示:

1 <= strs.length <= 104

0 <= strsi.length <= 100

strsi 仅包含小写字母


二、解法

使用哈希表

可以将每个单词,排一下序,然后相同排序的单词放到一起,最后,将每个list输出就好啦


完整代码

python 复制代码
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        dic = collections.defaultdict(list)
        for s in strs:
            dic[''.join(sorted(s))].append(s)
        return list(dic.values())

相关推荐
longlongzihan3 小时前
从LeetCode 70. 爬楼梯看动态规划:如何精准推导状态转移方程?
c++·算法·leetcode·动态规划
Rnan-prince8 小时前
LeetCode 股票买卖系列:一个动态规划状态机模板通吃四题
leetcode·动态规划
圣保罗的大教堂9 小时前
leetcode 3756. 连接非零数字并乘以其数字和 II 中等
leetcode
All for pursuit.13 小时前
【回溯-7】494.目标和
数据结构·c++·算法·leetcode
Tisfy14 小时前
LeetCode 0678.有效的括号字符串:O(n)+O(1)一次遍历
算法·leetcode·字符串·题解·贪心·括号匹配
Navigator_Z1 天前
LeetCode //C - 1278. Palindrome Partitioning III
c语言·算法·leetcode
青山木1 天前
Hot 100 --- 编辑距离
java·数据结构·算法·leetcode·动态规划
All for pursuit.1 天前
【回溯-4】46.全排列
数据结构·c++·算法·leetcode
All for pursuit.2 天前
【回溯-5】78.子集
数据结构·c++·算法·leetcode
代码什么用2 天前
LeetCode-560.和为 K 的子数组
算法·leetcode