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