【Python刷力扣hot100】49. Group Anagrams

问题

给定一个字符串数组 strs,将字母异位词组合在一起。返回的答案可以按任意顺序排列。

字母异位词(Anagram):由相同字母按照不同顺序排列组成的字符串,例如 "listen" 和 "silent"、"eat" 和 "tea" 均为字母异位词。

例1:

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

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

  • 解释:
    • There is no string in strs that can be rearranged to form "bat".
    • The strings "nat" and "tan" are anagrams as they can be rearranged to form each other.
    • The strings "ate", "eat", and "tea" are anagrams as they can be rearranged to form each other.

例2:

输入: strs = [""]

输出: [[""]]

例3:

输入: strs = ["a"]

输出: [["a"]]

约束条件:

  • 字符串数组 strs 的长度满足:1 ≤ strs.length ≤ 10⁴(即数组中至少有 1 个字符串,最多不超过 10000 个字符串)
  • 数组中每个字符串 strs[i] 的长度满足:0 ≤ strs [i].length ≤ 100(即单个字符串可能为空字符串,最长不超过 100 个字符)
  • 字符串 strs[i] 仅由小写英文字母组成(无大写字母、数字、符号等其他字符)

解:哈希表

  1. 设原始数据在list1中,可以把每个单词按字母排序,显然所有的字母异位词排序后会得到相同的单词。
  2. 把该集合存入哈希表(key:排序后的单词。value:原始单词)。但是相同的key只能有1个,所以value是一个存储了原始单词的list
  3. 遍历所有key,分别把每个key对应的value存入list2。list2就是我们要的结果

时间复杂度 O ( n k l o g k ) O(nklogk) O(nklogk): n n n是字符串数量, k k k是字符串的最大长度。需要进行 n n n次排序操作,一次排序操作的时间复杂度是 O ( k l o g k ) O(klogk) O(klogk)。

空间复杂度 O ( n k ) O(nk) O(nk):随着数组规模的增大,我们使用哈希表的空间也会等比增大,需要额外占用的空间也会增大。

python 复制代码
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        # 创建哈希表,key为排序后的字符串,value为原始字符串列表
        anagram_dict = {}
        for s in strs:
            # 对字符串按字母排序,作为哈希表的key
            sorted_str = ''.join(sorted(s))
            
            # 如果key已存在,将当前字符串添加到对应列表
            if sorted_str in anagram_dict:
                anagram_dict[sorted_str].append(s)
            # 如果key不存在,创建新的列表并添加当前字符串
            else:
                anagram_dict[sorted_str] = [s]
        # 将哈希表中的所有值(列表)组成新列表返回
        return list(anagram_dict.values())

参考

https://leetcode.cn/problems/group-anagrams

相关推荐
孟健14 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞16 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽19 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程1 天前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪1 天前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook1 天前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田2 天前
使用 pkgutil 实现动态插件系统
python
前端付豪2 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽2 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战2 天前
Pydantic配置管理最佳实践(一)
python