-
Notifications
You must be signed in to change notification settings - Fork 0
/
208-Implement_Trie_(Prefix_Tree).py
52 lines (39 loc) · 1.21 KB
/
208-Implement_Trie_(Prefix_Tree).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
49
50
51
52
class TrieNode:
def __init__(self, ch=""):
self.val = ch
self.is_word = False
self.children = dict()
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for ch in word:
if ch in node.children:
node = node.children[ch]
else:
next_node = TrieNode(ch=ch)
node.children[ch] = next_node
node = next_node
node.is_word = True
def search(self, word: str) -> bool:
node = self.root
for ch in word:
if ch in node.children:
node = node.children[ch]
else:
return False
return node.is_word
def startsWith(self, prefix: str) -> bool:
node = self.root
for ch in prefix:
if ch in node.children:
node = node.children[ch]
else:
return False
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)