Practice · Trie · 2 of 2

Word Dictionary with Wildcards

Write a class WordDictionary that stores lowercase words and finds them by pattern:

  • WordDictionary() makes an empty dictionary.
  • addWord(word) stores word.
  • search(word) returns true if some stored word matches word, and false otherwise. Here word may contain dots: each . matches any one letter, and every other letter must match itself. A match has exactly the same length.

Each test is a list of calls, starting with the constructor; the expected answer lists what each call returns (null for the constructor and for addWord).

Example 1

Calls
WordDictionary(), addWord("cat"), addWord("cart"), search("c.t"), search("c..t"), search("ca")
Returns
[null, null, null, true, true, false]
c.t matches "cat" and c..t matches "cart", but nothing matches ca: a match must have the same length.

Example 2

Calls
WordDictionary(), addWord("dog"), search(".o."), search("d.gs"), search(".")
Returns
[null, null, true, false, false]

Constraints

  • Stored words have 1 to 25 lowercase English letters.
  • Searched words have 1 to 25 characters, each a lowercase letter or ., with at most 2 dots.
  • A test makes at most 10⁴ calls.