211. Design Add and Search Words Data Structure
class TrieNode:
def __init__(self):
self.child = {}
self.is_word = False
class WordDictionary:
def __init__(self):
self.root = TrieNode()
def addWord(self, word):
cur = self.root
for c in word:
if c not in cur.child :
cur.child[c] = TrieNode()
cur = cur.child[c]
cur.is_word = True
def search(self, word):
return self.dfs(word, self.root)
def dfs(self, word, node):
if not word:
return node.is_word
if word[0] == ".":
return any(self.dfs(word[1:], child_node) for child_node in node.child.values())
else:
if word[0] in node.child:
return self.dfs(word[1:], node.child[word[0]])