Design Add and Search Words Data Structure - Problem
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 objectvoid addWord(word)- Adds word to the data structure, it can be matched laterbool search(word)- Returnstrueif there is any string in the data structure that matches word orfalseotherwise. word may contain dots '.' where dots can be matched with any letter
Input & Output
Example 1 — Basic Operations
$
Input:
operations = ["WordDictionary","addWord","addWord","addWord","search","search","search","search"], parameters = [[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
›
Output:
[null,null,null,null,false,true,true,true]
💡 Note:
Initialize dictionary, add 'bad', 'dad', 'mad'. Search 'pad' (false), 'bad' (true), '.ad' matches 'bad', 'dad', 'mad' (true), 'b..' matches 'bad' (true)
Example 2 — Wildcard Pattern
$
Input:
operations = ["WordDictionary","addWord","search","search"], parameters = [[],["a"],["."], ["a"]]
›
Output:
[null,null,true,true]
💡 Note:
Add 'a', search '.' matches any single character including 'a' (true), search 'a' finds exact match (true)
Example 3 — No Match
$
Input:
operations = ["WordDictionary","addWord","search"], parameters = [[],["abc"],["ab"]]
›
Output:
[null,null,false]
💡 Note:
Add 'abc', search 'ab' has different length than stored word, no match (false)
Constraints
- 1 ≤ word.length ≤ 25
- word in addWord consists of lowercase English letters
- word in search consist of '.' or lowercase English letters
- At most 104 calls will be made to addWord and search
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code