-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path049 Group Anagrams.py
39 lines (33 loc) · 1.01 KB
/
049 Group Anagrams.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
'''
Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Note:
For the return value, each inner list's elements must follow the lexicographic order.
All inputs will be in lower-case.
'''
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
map = {}
for i, v in enumerate(strs):
target = "".join(sorted(v))
if target not in map:
map[target]=[v]
else:
map[target].append(v)
result = []
for value in map.values():
result += [sorted(value)]
return result
if __name__ == "__main__":
assert Solution().groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]) == [['nat', 'tan'], ['bat'],
['ate', 'eat', 'tea']]