Question

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.

This is atrie question.

Idea

  • We need to add words and check for matches which hints at implementing a trie
  • The hard part about this question is handling the “.” operator which matches with any character
  • See Leetcode - Implement Trie (Prefix Tree) on how to implement a Trie with addWord and search
  • To handle the dot operator, we would essentially do a brute force dfs to try to match the .’s
    • We try all possible paths we can until we find a matching word or we exhaust all our options
    • To do so, iterate through each child of our current character
    • Call dfs on that character (where our dfs function is the body of our search function which accepts different arguments) where we pass
      • The remaining portion of the word that we are trying to match (our current position in the string + 1)
      • Our current node to access its children and end of word sentinal
    • If our dfs is successful return true, else return false

Solution