原题
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]