forked from DefiPanda/Leetcode-Py
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Anagrams.py
25 lines (24 loc) · 971 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
class Solution:
def anagrams(self, strs):
anagram_map, res = {}, []
for str in strs:
sorted_str = ("").join(sorted(str))
if sorted_str in anagram_map:
anagram_map[sorted_str].append(str)
else:
anagram_map[sorted_str] = [str]
for anagrams in anagram_map.values():
if len(anagrams) > 1:
res += anagrams
return res
# def anagrams(self, strs):
# """List comprehension may be more elegant but less readable here.
# """
# anagram_map = {}
# for str in strs:
# sorted_str = ("").join(sorted(str))
# if sorted_str in anagram_map:
# anagram_map[sorted_str].append(str)
# else:
# anagram_map[sorted_str] = [str]
# return [anagram for anagrams in anagram_map.values() if len(anagrams) > 1 for anagram in anagrams]