-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautocomplete.py
39 lines (34 loc) · 1.21 KB
/
autocomplete.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
class Node:
def __init__(self, children, isWord):
self.children = children
self.isWord = isWord
class Solution:
def __init__(self):
self.trie = None
def build(self, words):
self.trie = Node({}, False)
for word in words:
current = self.trie
for char in word:
if not char in current.children:
current.children[char] = Node({}, False)
current = current.children[char]
current.isWord = True
def autocomplete(self, prefix):
current = self.trie
for char in prefix:
if not char in current.children:
return []
current = current.children[char]
return self._findWordsFromNode(current, prefix)
def _findWordsFromNode(self, node, prefix):
words = []
if node.isWord:
words += [prefix]
for char in node.children:
words += self._findWordsFromNode(node.children[char], prefix + char)
return words
s = Solution()
s.build(['dog', 'dark', 'cat', 'door', 'dodge', 'car', 'apple', 'mobile', 'phone', 'smart phone', 'pc', 'graphic card'])
print(s.autocomplete('ca'))
#['dog', 'door', 'dodge']