-
Notifications
You must be signed in to change notification settings - Fork 2
/
00208-implement_trie_prefix_tree.py
65 lines (48 loc) · 1.63 KB
/
00208-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
53
54
55
56
57
58
59
60
61
62
63
64
65
# 208: Implement Trie Prefix Tree
# https://leetcode.com/problems/implement-trie-prefix-tree
class TrieNode:
def __init__(self) -> None:
self.children: TrieNode[26] = []
self.isWord = False
for i in range(26):
self.children.append(None)
self.isWord = False
class Trie:
def __init__(self):
self.root: TrieNode = TrieNode()
def insert(self, word: str) -> None:
node: TrieNode = self.root
current = 0;
for i in range(len(word)):
current = ord(word[i]) - ord('a')
if node.children[current] == None:
node.children[current] = TrieNode()
node = node.children[current];
node.isWord = True
def search(self, word: str) -> bool:
node: TrieNode = self.root
current = 0;
for i in range(len(word)):
current = ord(word[i]) - ord('a')
if node.children[current] == None:
return False
node = node.children[current];
return node.isWord
def startsWith(self, prefix: str) -> bool:
node: TrieNode = self.root
current = 0;
for i in range(len(prefix)):
current = ord(prefix[i]) - ord('a')
if node.children[current] == None:
return False
node = node.children[current];
return True
if __name__ == "__main__":
trie: Trie = Trie()
# OPERATIONS
trie.insert("apple")
print(trie.search("apple"))
print(trie.search("app"))
print(trie.startsWith("app"))
trie.insert("app")
print(trie.search("app"))