-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie.py
More file actions
42 lines (34 loc) · 1.12 KB
/
Trie.py
File metadata and controls
42 lines (34 loc) · 1.12 KB
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
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.isEnd = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
curr = self.root
for char in word:
ind = ord(char) - ord('a')
if curr.children[ind] is None:
curr.children[ind] = TrieNode()
curr = curr.children[ind]
curr.isEnd = True
def search(self, word: str) -> bool:
curr = self.root
for char in word:
ind = ord(char) - ord('a')
if curr.children[ind] is None: return False
curr = curr.children[ind]
return curr.isEnd
def startsWith(self, prefix: str) -> bool:
curr = self.root
for char in prefix:
ind = ord(char) - ord('a')
if curr.children[ind] is None: return False
curr = curr.children[ind]
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)