forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanagrams.py
More file actions
26 lines (24 loc) · 774 Bytes
/
anagrams.py
File metadata and controls
26 lines (24 loc) · 774 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
# Time: O(nlogg) = O(n / g * glogg), g is 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().anagrams(["cat", "dog", "act", "mac"])
print result