-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimplement_trie.py
34 lines (28 loc) · 1.02 KB
/
implement_trie.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
from problems.util.trie_node import TrieNode
class Trie:
def __init__(self):
self.root = TrieNode('')
def insert(self, word: str) -> None:
# Check if the word is already present
if self.search(word):
return
current = self.root
for c in word:
if not current.children[ord(c) - ord('a')]:
current.children[ord(c) - ord('a')] = TrieNode(c)
current = current.children[ord(c) - ord('a')]
current.isWord = True
def search(self, word: str) -> bool:
current = self.root
for c in word:
if not current.children[ord(c) - ord('a')]:
return False
current = current.children[ord(c) - ord('a')]
return current.isWord
def startsWith(self, prefix: str) -> bool:
current = self.root
for c in prefix:
if not current.children[ord(c) - ord('a')]:
return False
current = current.children[ord(c) - ord('a')]
return True