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