-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
34 lines (22 loc) · 879 Bytes
/
main.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
28
29
30
31
32
33
34
"""
49. Group Anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Time complexity: O(clogc * s)
Space complexity: O(s * c)
"""
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
if not strs:
return []
groups = {}
for str in strs:
key = tuple(sorted(str))
if key in groups:
groups[key].append(str)
else:
groups[key] = [str]
result = []
for key, value in groups.items():
result.append(value)
return result