for char in word: if char notin basic_trie: returnFalse current_node = current_node[char] return current_node['word_end']
测试is_word:
python
1 2 3 4 5 6
test_words = ['ap', 'add'] for word in test_words: if is_word(word): print('"{}" is a word.'.format(word)) else: print('"{}" is not a word.'.format(word))
# Add words for word in word_list: word_trie.add(word)
# Test words test_words = ['bear', 'goo', 'good', 'goos'] for word in test_words: if word_trie.exists(word): print('"{}" is a word.'.format(word)) else: print('"{}" is not a word.'.format(word))
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 char in word: if char notin node.children: node.children[char] = TrieNode() node = node.children[char] node.is_word = True
defsearch(self, word: str) -> bool: """ Returns if the word is in the trie. """ node = self.root for char in word: if char notin node.children: returnFalse node = node.children[char] return node.is_word
defstartsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ node = self.root for char in prefix: if char in node.children: node = node.children[char] 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)