def__init__(self): """ Initialize your data structure here. """ self.root = TrieNode()
definsert(self, word): """ Inserts a word into the trie. :type word: str :rtype: None """ cur = self.root for char in word: if cur.children[ord(char) - ord('a')] isNone: cur.children[ord(char) - ord('a')] = TrieNode() cur = cur.children[ord(char) - ord('a')] cur.isEnd = True
defsearch(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ cur = self.root for char in word: if cur.children[ord(char) - ord('a')]: cur = cur.children[ord(char) - ord('a')] else: returnFalse return cur isnotNoneand cur.isEnd
defstartsWith(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool """ cur = self.root for char in prefix: if cur.children[ord(char) - ord('a')]: cur = cur.children[ord(char) - ord('a')] else: returnFalse return cur isnotNone
# 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)
def__init__(self): """ Initialize your data structure here. """ self.trie = {}
definsert(self, word: str) -> None: """ Inserts a word into the trie. """ trie = self.trie for ch in word: if ch notin trie: trie[ch] = {} trie = trie[ch] trie['end'] = True defsearch(self, word: str) -> bool: """ Returns if the word is in the trie. """ trie = self.trie for ch in word: if ch in trie: trie = trie[ch] else: returnFalse return'end'in trie
defstartsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ trie = self.trie for ch in prefix: if ch in trie: trie = trie[ch] else: returnFalse 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)