-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path#0208 Implement Trie (Prefix Tree).py
More file actions
73 lines (63 loc) · 2.33 KB
/
#0208 Implement Trie (Prefix Tree).py
File metadata and controls
73 lines (63 loc) · 2.33 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class TrieNode:
def __init__(self):
"""
Initialize a TrieNode with an empty dictionary for children
and a boolean flag for marking the end of a word.
"""
self.children = {} # Dictionary to hold child nodes
self.end_of_word = False # Flag to mark the end of a word
class Trie:
def __init__(self):
"""
Initialize a Trie with a root TrieNode.
"""
self.root = TrieNode() # Root node of the Trie
def insert(self, word: str) -> None:
"""
Insert a word into the Trie.
Args:
word (str): The word to be inserted.
"""
curr = self.root # Start from the root node
for c in word:
# If the character is not in the current node's children, add it
if c not in curr.children:
curr.children[c] = TrieNode()
# Move to the child node
curr = curr.children[c]
# Mark the end of the word at the final node
curr.end_of_word = True
def search(self, word: str) -> bool:
"""
Search for a word in the Trie.
Args:
word (str): The word to search for.
Returns:
bool: True if the word exists in the Trie, False otherwise.
"""
curr = self.root # Start from the root node
for c in word:
# If the character is not in the current node's children, the word does not exist
if c not in curr.children:
return False
# Move to the child node
curr = curr.children[c]
# Return True if the end of the word is marked
return curr.end_of_word
def startsWith(self, prefix: str) -> bool:
"""
Check if there is any word in the Trie that starts with the given prefix.
Args:
prefix (str): The prefix to check for.
Returns:
bool: True if there is a word starting with the prefix, False otherwise.
"""
curr = self.root # Start from the root node
for c in prefix:
# If the character is not in the current node's children, the prefix does not exist
if c not in curr.children:
return False
# Move to the child node
curr = curr.children[c]
# Return True if the prefix was found
return True