-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprefix_tries.py
53 lines (47 loc) · 1.2 KB
/
prefix_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
43
44
45
46
47
48
49
50
51
52
53
class Node:
def __init__(self, val=None):
self.isEnd = False
self.neighbours = {}
class Trie(object):
def __init__(self):
self.root = Node()
def insert(self, word):
"""
:type word: str
:rtype: None
"""
curr = self.root
for i in word:
if i not in curr.neighbours:
curr.neighbours[i] = Node(i)
curr = curr.neighbours[i]
curr.isEnd = True
def search(self, word):
"""
:type word: str
:rtype: bool
"""
curr = self.root
for i in word:
if i in curr.neighbours:
curr = curr.neighbours[i]
else:
return False
return curr.isEnd
def startsWith(self, prefix):
"""
:type prefix: str
:rtype: bool
"""
curr = self.root
for i in prefix:
if i in curr.neighbours:
curr = curr.neighbours[i]
else:
return False
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)