java.lang.Object
g0201_0300.s0211_design_add_and_search_words_data_structure.WordDictionary

public class WordDictionary extends Object
211 - Design Add and Search Words Data Structure.<p>Medium</p> <p>Design a data structure that supports adding new words and finding if a string matches any previously added string.</p> <p>Implement the <code>WordDictionary</code> class:</p> <ul> <li><code>WordDictionary()</code> Initializes the object.</li> <li><code>void addWord(word)</code> Adds <code>word</code> to the data structure, it can be matched later.</li> <li><code>bool search(word)</code> Returns <code>true</code> if there is any string in the data structure that matches <code>word</code> or <code>false</code> otherwise. <code>word</code> may contain dots <code>'.'</code> where dots can be matched with any letter.</li> </ul> <p><strong>Example:</strong></p> <p><strong>Input</strong></p> <pre><code> [&quot;WordDictionary&quot;,&quot;addWord&quot;,&quot;addWord&quot;,&quot;addWord&quot;,&quot;search&quot;,&quot;search&quot;,&quot;search&quot;,&quot;search&quot;] [ [],[&quot;bad&quot;],[&quot;dad&quot;],[&quot;mad&quot;],[&quot;pad&quot;],[&quot;bad&quot;],[&quot;.ad&quot;],[&quot;b..&quot;]] </code></pre> <p><strong>Output</strong></p> <pre><code> [null,null,null,null,false,true,true,true] </code></pre> <p><strong>Explanation</strong></p> <pre><code> WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord(&quot;bad&quot;); wordDictionary.addWord(&quot;dad&quot;); wordDictionary.addWord(&quot;mad&quot;); wordDictionary.search(&quot;pad&quot;); // return False wordDictionary.search(&quot;bad&quot;); // return True wordDictionary.search(&quot;.ad&quot;); // return True wordDictionary.search(&quot;b..&quot;); // return True </code></pre> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= word.length <= 500</code></li> <li><code>word</code> in <code>addWord</code> consists lower-case English letters.</li> <li><code>word</code> in <code>search</code> consist of <code>'.'</code> or lower-case English letters.</li> <li>At most <code>50000</code> calls will be made to <code>addWord</code> and <code>search</code>.</li> </ul>
  • Constructor Details

    • WordDictionary

      public WordDictionary()
  • Method Details

    • addWord

      public void addWord(String word)
    • search

      public boolean search(String word)