-
Notifications
You must be signed in to change notification settings - Fork 1
/
49. Group Anagrams.py
44 lines (37 loc) · 1.04 KB
/
49. Group 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from typing import List
"""
Remember python has very nice data structures.
You were thinking of a dictionary, but you implemented it as a list, used breaks and things...
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
g = {}
for s in strs:
key = tuple(sorted(s))
if key in g:
g[key].append(s)
else:
g[key] = [s]
return g.values()
"""
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
output = []
for s in strs:
flag = False
sSorted = sorted(s)
for t in output:
if sSorted == t[0]:
t.append(s)
flag = True
break
if not flag:
output.append([sSorted,s])
return [l[1::] for l in output]
inputs = [
["eat","tea","tan","ate","nat","bat"],
[""],
["a"]
]
for strs in inputs:
print(strs)
print(Solution().groupAnagrams(strs))