-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy path0208-implement-trie-prefix-tree.py
56 lines (49 loc) · 1.33 KB
/
0208-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
# insert()
# time complexity: O(l)
# space complexity: O(l)
# search()
# time complexity: O(l)
# space complexity: O(1)
# search prefix()
# time complexity: O(l)
# space complexity: O(1)
class TrieNode:
def __init__(self, char: str = ""):
self.char = char
self.children = {}
self.isEnd = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str):
node = self.root
for c in word:
if c in node.children:
node = node.children[c]
else:
newNode = TrieNode()
node.children[c] = newNode
node = newNode
node.isEnd = True
def search(self, word: str):
node = self.root
for c in word:
if c not in node.children:
return False
node = node.children[c]
return node.isEnd
def startsWith(self, prefix: str):
node = self.root
for c in prefix:
if c not in node.children:
return False
node = node.children[c]
return True
# Your Trie object will be instantiated and called as such:
trie = Trie()
trie.insert("apple")
print(trie.search("apple"))
print(trie.search("app"))
print(trie.startsWith("app"))
trie.insert("app")
print(trie.search("app"))