-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathanagrams.py
More file actions
23 lines (18 loc) · 712 Bytes
/
anagrams.py
File metadata and controls
23 lines (18 loc) · 712 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
def groupAnagrams(self, strs):
# Input: strs = ["eat","tea","tan","ate","nat","bat"]
# Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
anagrams = {}
for word in strs:
sorted_word = ''.join(sorted(word))
if sorted_word in anagrams:
anagrams[sorted_word].append(word)
else:
anagrams[sorted_word] = [word]
anagrams = list(anagrams.values())
print(anagrams)
strs = ["eat","tea","tan","ate","nat","bat"]
# strs = ['','']
print(Solution().groupAnagrams(strs))
## Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
# [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]