class WordDictionary(object): def __init__(self): """ initialize your data structure here. """ self.trie = Trie() def addWord(self, word): """ Adds a word into the data structure. :type word: str :rtype: void """ self.trie.insert(word) def search(self, word): """ Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. :type word: str :rtype: bool """ def search(idx, node): if idx == len(word): return node.is_leaf ch = word[idx] if ch != ".": if ch not in node.map_: return False else: return search(idx + 1, node.map_[ch]) else: for k, v in node.map_.items(): if search(idx + 1, v): return True return False return search(0, self.trie.root)
def test1(): trie = Trie() trie.insert("apple") assert trie.search("apple") == True
def test2(): trie = Trie() trie.insert("apple") assert trie.search("app") == False
def test3(): trie = Trie() trie.insert("apple") assert trie.startsWith("app") == True