File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Trie :
2+
3+ def __init__ (self ):
4+ """
5+ Initialize your data structure here.
6+ """
7+ self .root = {}
8+ self .end_of_word = "#"
9+
10+ def insert (self , word : str ) -> None :
11+ """
12+ Inserts a word into the trie.
13+ """
14+ node = self .root
15+ for char in word :
16+ node = node .setdefault (char , {})
17+ node [self .end_of_word ] = self .end_of_word
18+
19+ def search (self , word : str ) -> bool :
20+ """
21+ Returns if the word is in the trie.
22+ """
23+ node = self .root
24+ for char in word :
25+ if char not in node :
26+ return False
27+ node = node [char ]
28+ return self .end_of_word in node
29+
30+ def startsWith (self , prefix : str ) -> bool :
31+ """
32+ Returns if there is any word in the trie that starts with the given prefix.
33+ """
34+ node = self .root
35+ for char in prefix :
36+ if char not in node :
37+ return False
38+ node = node [char ]
39+ return True
You can’t perform that action at this time.
0 commit comments