File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
implement-trie-prefix-tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ # https://leetcode.com/problems/implement-trie-prefix-tree/
2
+
3
+ from collections import defaultdict
4
+
5
+
6
+ class TrieNode :
7
+ def __init__ (self ):
8
+ self .is_word = False
9
+ self .children = defaultdict (TrieNode )
10
+
11
+
12
+ class Trie :
13
+ def __init__ (self ):
14
+ self .root = TrieNode ()
15
+
16
+ def insert (self , word : str ) -> None :
17
+ curr = self .root
18
+
19
+ for w in word :
20
+ curr = curr .children [w ]
21
+
22
+ curr .is_word = True
23
+
24
+ def search (self , word : str ) -> bool :
25
+ curr = self .root
26
+
27
+ for w in word :
28
+ if w not in curr .children :
29
+ return False
30
+ curr = curr .children [w ]
31
+
32
+ return curr .is_word
33
+
34
+ def startsWith (self , prefix : str ) -> bool :
35
+ curr = self .root
36
+
37
+ for p in prefix :
38
+ if p not in curr .children :
39
+ return False
40
+ curr = curr .children [p ]
41
+
42
+ return True
43
+
44
+ # Your Trie object will be instantiated and called as such:
45
+ # obj = Trie()
46
+ # obj.insert(word)
47
+ # param_2 = obj.search(word)
48
+ # param_3 = obj.startsWith(prefix)
You can’t perform that action at this time.
0 commit comments