Design Add and Search Words Data Structure
MediumTries
Design a WordDictionary class that stores words and answers searches in which . acts as a wildcard.
WordDictionary()creates an empty dictionary.addWord(word)storesword. Adding the same word twice has no extra effect.search(word)returnsTrueif some stored word matchesword, andFalseotherwise.
A stored word matches the search pattern when both have the same length and, at every position, the pattern either has the same letter or has ., which matches any single letter. A . never matches an empty position, so the lengths must be equal. Only words added before the search count.
The examples list the calls made in order, and the output lists each call's return value (None for the constructor and addWord).
Example 1
- Input:
- WordDictionary(); addWord("cat"); addWord("cot"); addWord("cart"); search("c.t"); search("ca.t"); search("c..."); search("cut")
- Output:
- [None, None, None, None, True, True, True, False]
- Explanation
c.tmatches bothcatandcot.ca.tandc...are four letters long and matchcart.cutcontains no dot and was never added, so it fails.
Example 2
- Input:
- WordDictionary(); addWord("go"); search("."); search(".."); search("go.")
- Output:
- [None, None, False, True, False]
- Explanation
- Each dot matches exactly one letter, so only the two-letter pattern
..can matchgo;.is too short andgo.is too long.
Example 3
- Input:
- WordDictionary(); search("a"); addWord("a"); search("a"); search(".")
- Output:
- [None, False, None, True, True]
- Explanation
- The first search runs before anything is stored, so it fails. After
ais added, both the exact search and the single dot match it.
Constraints
1 <= word.length <= 25wordinaddWordconsists of lowercase English letterswordinsearchconsists of lowercase English letters or'.'- Each
searchpattern contains at most2dots - At most
10^4calls are made toaddWordandsearchin total