forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathanagrams.py
More file actions
27 lines (24 loc) · 762 Bytes
/
anagrams.py
File metadata and controls
27 lines (24 loc) · 762 Bytes
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
# Time: O(n * glogg), g is the max size of groups.
# Space: O(n)
#
# Given an array of strings, return all groups of strings that are anagrams.
#
# Note: All inputs will be in lower-case.
#
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
anagrams_map, result = collections.defaultdict(list), []
for s in strs:
sorted_str = ("").join(sorted(s))
anagrams_map[sorted_str].append(s)
for anagram in anagrams_map.values():
anagram.sort()
result.append(anagram)
return result
if __name__ == "__main__":
result = Solution().groupAnagrams(["cat", "dog", "act", "mac"])
print result