definsert(self, word: str) -> None: """ Inserts a word into the trie. """ node = self.root for ch in word: if ch notin node.children: node.children[ch] = TrieNode() node = node.children[ch] node.isword = True
Trie查找
对于前缀🌲Trie, 给定一个单词,和插入的过程类似,一个字符一个字符找
若中途有个字符没有对应结点,则不含该单词
若字符串遍历完了,都有对应节点,但最后一个字符对应的结点没有被标记为True,也不含该单词
1 2 3 4 5 6 7 8 9 10 11
defsearch(self, word: str) -> bool: """ Returns if the word is in the trie. """ node = self.root for ch in word: if ch notin node.children: returnFalse node = node.children[ch] ifnot node.isword: returnFalse returnTrue
classTrieNode: def__init__(self): """ Initialize your data structure here. """ self.children = {} self.isword = False
classTrie:
def__init__(self): """ Initialize your data structure here. """ self.root = TrieNode()
definsert(self, word: str) -> None: """ Inserts a word into the trie. """ node = self.root for ch in word: if ch notin node.children: node.children[ch] = TrieNode() node = node.children[ch] node.isword = True
defsearch(self, word: str) -> bool: """ Returns if the word is in the trie. """ node = self.root for ch in word: if ch notin node.children: returnFalse node = node.children[ch] ifnot node.isword: returnFalse returnTrue
defstartsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ node = self.root for ch in prefix: if ch notin node.children: returnFalse node = node.children[ch] 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)