def__init__(self): """ Initialize your data structure here. """ self.root = {} # 特殊标记 self.word_end = -1
definsert(self, word: str) -> None: """ Inserts a word into the trie. """ cur_node = self.root for char in word: ifnot char in cur_node: cur_node[char] = {} cur_node = cur_node[char] cur_node[self.word_end] = True
defsearch(self, word: str) -> bool: """ Returns if the word is in the trie. """ cur_node = self.root for char in word: if char notin cur_node: returnFalse cur_node = cur_node[char] if self.word_end notin cur_node: returnFalse returnTrue
defstartsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ cur_node = self.root for char in prefix: ifnot char in cur_node: returnFalse cur_node = cur_node[char] returnTrue
# 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)