原题
Given an array of strings, group anagrams together.
Example:
Input: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],
Output:
[
[“ate”,“eat”,“tea”],
[“nat”,“tan”],
[“bat”]
]
Note:
All inputs will be in lowercase.
The order of your output does not matter.
解法
构造defaultdict, 用列表作为它的value, 将单词排序后转化为元组作为它的key
Time: O(n)
Space: O(1)
代码
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
d = collections.defaultdict(list)
for s in strs:
tup = tuple(sorted(s))
d[tup].append(s)
return [d[k] for k in d]
本文深入探讨了一种高效的Anagram分组算法,通过使用defaultdict数据结构,将字符串排序后作为键,实现了对输入字符串数组中所有Anagram的快速分组。此方法时间复杂度为O(n),空间复杂度为O(1),适用于处理大规模数据集。
384

被折叠的 条评论
为什么被折叠?



