forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
anagrams.py
27 lines (25 loc) · 785 Bytes
/
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
# Time: O(n)
# 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:
# @param strs, a list of strings
# @return a list of strings
def anagrams(self, strs):
anagrams_map, result = {}, []
for s in strs:
sorted_str = ("").join(sorted(s))
if sorted_str in anagrams_map:
anagrams_map[sorted_str].append(s)
else:
anagrams_map[sorted_str] = [s]
for anagram in anagrams_map.values():
if len(anagram) > 1:
result += anagram
return result
if __name__ == "__main__":
result = Solution().anagrams(["cat", "dog", "act", "mac"])
print result