-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0049-group-anagrams.py
More file actions
32 lines (28 loc) · 947 Bytes
/
0049-group-anagrams.py
File metadata and controls
32 lines (28 loc) · 947 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
28
29
30
31
32
# time complexity: O(nklogn)
# space complexity: O(nk)
from collections import defaultdict
from typing import List
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
wordMap = defaultdict(list)
for word in strs:
key = ''.join(sorted(word))
wordMap[key].append(word)
return [row for row in wordMap.values()]
# time complexity: O(nk)
# space complexity: O(nk)
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
result = defaultdict(list)
for s in strs:
count = [0] * 26
for c in s:
count[ord(c) - ord("a")] += 1
result[tuple(count)].append(s)
return list(result.values())
strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
print(Solution().groupAnagrams(strs))
strs = [""]
print(Solution().groupAnagrams(strs))
strs = ["a"]
print(Solution().groupAnagrams(strs))