-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path208_implement_trie_prefix_tree.py
More file actions
54 lines (46 loc) · 1.23 KB
/
Copy path208_implement_trie_prefix_tree.py
File metadata and controls
54 lines (46 loc) · 1.23 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
43
44
45
46
47
48
49
50
51
52
53
54
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = {}
self.end_word = "#"
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
node = self.root
for w in word:
node = node.setdefault(w, {})
node[self.end_word] = self.end_word
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
node = self.root
for w in word:
node = node.get(w)
if node is None:
return False
return self.end_word in node
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
node = self.root
for w in prefix:
node = node.get(w)
if node is None:
return False
return True
def test():
s = Trie()
s.insert("apple")
assert not s.search("app")
assert s.search("apple")
assert s.startsWith("app")
assert s.startsWith("apple")
s.insert("app")
assert s.search("app")
if __name__ == "__main__":
test()