Skip to content

Commit 1c3a16b

Browse files
committed
adding implement trie prefix tree
1 parent 70de401 commit 1c3a16b

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Trie:
2+
3+
def __init__(self):
4+
self.children = {}
5+
self.is_end = False
6+
7+
def insert(self, word: str) -> None:
8+
node = self
9+
10+
for c in word:
11+
if c not in node.children:
12+
node.children[c] = Trie()
13+
node = node.children[c]
14+
15+
node.is_end = True
16+
17+
18+
def search(self, word: str) -> bool:
19+
node = self
20+
21+
for c in word:
22+
if c not in node.children:
23+
return False
24+
node = node.children[c]
25+
26+
return node.is_end
27+
28+
def startsWith(self, prefix: str) -> bool:
29+
node = self
30+
for c in prefix:
31+
if c not in node.children:
32+
return False
33+
node = node.children[c]
34+
return True
35+
36+
37+
38+
# Your Trie object will be instantiated and called as such:
39+
# obj = Trie()
40+
# obj.insert(word)
41+
# param_2 = obj.search(word)
42+
# param_3 = obj.startsWith(prefix)

0 commit comments

Comments
 (0)