-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathm1268.py
48 lines (38 loc) · 1.28 KB
/
m1268.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
45
46
47
48
class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
trie = {}
products.sort()
for product in products :
curr = trie
for c in product :
if c not in curr :
curr[c] = {}
curr = curr[c]
curr[False] = True
output = []
word = []
for c in searchWord :
temp = []
if c not in trie :
break
trie = trie[c]
word.append(c)
self.counter = 3
self.collectWordsFromPoint(trie, word, temp)
output.append(temp)
while len(output) < len(searchWord) :
output.append([])
return output
def collectWordsFromPoint(self, trie: dict, current: List[str], output: List[str]) -> None :
if not self.counter :
return
if not trie :
return
if False in trie :
output.append(''.join(current))
self.counter -= 1
for letter, branch in trie.items() :
if letter :
current.append(letter)
self.collectWordsFromPoint(branch, current, output)
current.pop()