Group Anagrams

Group Anagrams

dict solution - 172ms

1
2
3
4
5
6
7
8
9
10
11
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
ret = {}
for s in sorted(strs):
key = tuple(sorted(s))
ret[key] = ret.get(key, []) + [s]
return ret.values()

defaultdict solution - 128ms

1
2
3
4
5
6
7
import collections
class Solution(object):
def groupAnagrams(self, strs):
groups = collections.defaultdict(list)
for s in strs:
groups[tuple(sorted(s))].append(s)
return map(sorted, groups.values())

itertools solution - 156ms

1
2
3
4
import itertools
class Solution(object):
def groupAnagrams(self, strs):
return [sorted(g) for _, g in itertools.groupby(sorted(strs, key=sorted), sorted)]

test code

1
2
3
4
In [460]: s = Solution(); t = s.groupAnagrams(["eat","tea","tan","ate","nat","bat"])
In [461]: t
Out[461]: [['bat'], ['ate', 'eat', 'tea'], ['nat', 'tan']]

leet code

Python中collections.defaultdict()使用

理解 Python 语言中的 defaultdict