Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the WordDictionary
class:
WordDictionary()
Initializes the object.void addWord(word)
Adds word
to the data structure, it can be matched later.bool search(word)
Returns true
if there is any string in the data structure that matches word
or false
otherwise. word
may contain dots '.'
where dots can be matched with any letter.Q: Any restrictions on the length of the words? A: No specific restrictions mentioned in the problem.
Q: Will the characters always be lowercase English letters? A: Yes, that’s the assumption based on typical constraints of the problem.
Q: Can word
contain both normal characters and dots in any position?
A: Yes, word
can be composed of lowercase English letters in addition to the dot (.
) wildcard character.
.
wildcard, we need a recursive search function..
, recursively search all possible paths for the children nodes.class TrieNode:
def __init__(self):
self.children = {}
self.end_of_word = False
class WordDictionary:
def __init__(self):
self.root = TrieNode()
def addWord(self, word: str) -> None:
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.end_of_word = True
def search(self, word: str) -> bool:
return self._search_recursive(self.root, word, 0)
def _search_recursive(self, node: TrieNode, word: str, index: int) -> bool:
if index == len(word):
return node.end_of_word
if word[index] == '.':
for child in node.children.values():
if self._search_recursive(child, word, index + 1):
return True
else:
char = word[index]
if char in node.children:
return self._search_recursive(node.children[char], word, index + 1)
return False
.
wildcard).This solution efficiently handles the requirements using a Trie along with recursive search to cater to the .
wildcard.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?