-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTrie.py
More file actions
32 lines (28 loc) · 818 Bytes
/
Trie.py
File metadata and controls
32 lines (28 loc) · 818 Bytes
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
class Trie:
def __init__(self):
self.sons = {}
def insert(self, word: str) -> None:
curr = self.sons
for x in word:
if x not in curr:
curr[x] = {}
curr = curr[x]
curr['*'] = '*'
def search(self, word: str) -> bool:
return self.startsWith(word+'*')
def startsWith(self, prefix: str) -> bool:
curr = self.sons
for x in prefix:
if x in curr:
curr = curr[x]
else:
return False
return True
##################################################
# Example code
##################################################
obj = Trie()
for word in ['cat','good','god','go','goodness']:
obj.insert(word)
print(obj.search('good'))
print(obj.startsWith('g'))