This repository was archived by the owner on Oct 16, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathimplement_trie.py
More file actions
52 lines (47 loc) · 1.43 KB
/
implement_trie.py
File metadata and controls
52 lines (47 loc) · 1.43 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
# we are creating Trie Data Structure and implementing various methods of the Data Structure
class TrieNode:
def __init__(self, val):
self.val = val
self.isEnd = False
self.children = [None for i in range(26)]
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode('*')
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
node = self.root
for c in word:
x = ord(c) - ord('a')
if node.children[x] is None:
node.children[x] = TrieNode(c)
node = node.children[x]
node.isEnd = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
node = self.root
for c in word:
x = ord(c) - ord('a')
if node.children[x] is not None:
node = node.children[x]
else:
return False
return node.isEnd
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 c in prefix:
x = ord(c) - ord('a')
if node.children[x] is not None:
node = node.children[x]
else:
return False
return True