-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroupAnagrams.py
More file actions
37 lines (30 loc) · 1.07 KB
/
groupAnagrams.py
File metadata and controls
37 lines (30 loc) · 1.07 KB
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
35
36
37
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
d = defaultdict(list)
for s in strs:
sorted_s = ''.join(sorted(s))
d[sorted_s].append(s)
return d.values()
def groupAnagrams2(self, strs: List[str]) -> List[List[str]]:
mainDict = {}
ans = []
for currStr in strs:
currSorted = ''.join(sorted(currStr))
if currSorted not in mainDict:
mainDict[currSorted] = [] + [currStr]
else:
mainDict[currSorted] = mainDict[currSorted] + [currStr]
return mainDict.values()
# slowest
def groupAnagrams3(self, strs: List[str]) -> List[List[str]]:
groups = {}
ana = []
for word in strs:
hashed = ''.join(sorted(word))
if hashed in groups:
groups[hashed].append(word)
else:
groups[hashed] = [word]
for li in groups.values():
ana.append(li)
return ana