Talentd
FleetCode

211. Design Add and Search Words Data Structure

Medium48.9% acceptance13 companies

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.

Example:

Input
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
Output
[null,null,null,null,false,true,true,true]

Explanation
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // return False
wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return True

Constraints:

  • 1 <= word.length <= 25
  • word in addWord consists of lowercase English letters.
  • word in search consist of '.' or lowercase English letters.
  • There will be at most 2 dots in word for search queries.
  • At most 104 calls will be made to addWord and search.

Hints open one at a time

Hint 1
You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.
19:50
Still stuck?Read 5 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class WordDictionary:
2
3 def __init__(self):
4
5
6 def addWord(self, word: str) -> None:
7
8
9 def search(self, word: str) -> bool:
10
11
12
13# Your WordDictionary object will be instantiated and called as such:
14# obj = WordDictionary()
15# obj.addWord(word)
16# param_2 = obj.search(word)
Starter codePython 3Spaces: 4
Examples
Input
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
Your code is saved on this device.Solution