General
211 Word Search
class Node:
def __init__(self):
self.children = collections.defaultdict(Node)
self.isWord = False
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = Node()
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
p = self.root
for ch in word:
p = p.children[ch]
p.isWord = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""
p = self.root
for i, ch in enumerate(word):
if ch == '.':
for j in range(26):
ch_new = chr(ord('a') + j)
if p.children[ch] and self.search(word[:i] + ch_new + word[i+1:]):
return True
return False
else:
if not p.children[ch]:
return False
p = p.children[ch]
return p.isWord212 Word Search II
Last updated