-
Notifications
You must be signed in to change notification settings - Fork 0
/
tries.py
42 lines (32 loc) · 1013 Bytes
/
tries.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
# Also called, prefix trees.
# Tries have tree like structure.
# These were basically built for storing and searching strings.
class TrieNode:
def __init__(self):
self.children = {}
self.word = False
class Trie:
def __init__(self) -> None:
self.root = TrieNode()
def insert(self, word) -> None:
node = self.root
for c in word:
if c not in node.children:
node.children[c] = TrieNode()
node = node.children[c]
node.word = True
return self.root
def search(self, word) -> bool:
node = self.root
for c in word:
if c not in node.children:
return False
node = node.children[c]
return node.word
def startsWith(self, prefix) -> bool:
node = self.root
for c in prefix:
if c not in node.children:
return False
node = node.children[c]
return True