-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path208. Implement Trie (Prefix Tree).py
More file actions
42 lines (32 loc) · 1.07 KB
/
208. Implement Trie (Prefix Tree).py
File metadata and controls
42 lines (32 loc) · 1.07 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
#https://www.jianshu.com/p/d9972db1571f dict tree 图示
class TrieNode:
def __init__(self):
self.child = {} #store every inserted word's letter
self.is_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
node =self.root
for letter in word:
if letter not in node.child:
node.child[letter]=TrieNode()
node = node.child[letter]
node.is_word =True
def find(self,word): #return found node or None
node = self.root
for letter in word:
node=node.child.get(letter)
if not node:
return None
return node
def search(self, word: str) -> bool:
node = self.find(word)
return node is not None and node.is_word
def startsWith(self, prefix: str) -> bool:
return self.find(prefix) is not None
# 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)