-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimplement_trie.py
More file actions
33 lines (28 loc) · 877 Bytes
/
implement_trie.py
File metadata and controls
33 lines (28 loc) · 877 Bytes
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
class TrieNode(object):
def __init__(self):
self.children = {}
self.end = False
class Trie:
def __init__(self):
self.child = TrieNode()
def insert(self, word: str) -> None:
curr = self.child
for char in word:
if char not in curr.children:
curr.children[char] = TrieNode()
curr = curr.children[char]
curr.end = True
def search(self, word: str) -> bool:
curr = self.child
for char in word:
if char not in curr.children:
return False
curr = curr.children[char]
return curr.end
def startsWith(self, prefix: str) -> bool:
curr = self.child
for char in prefix:
if char not in curr.children:
return False
curr = curr.children[char]
return True