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 3 dots in word for search queries.
  • At most 104 calls will be made to addWord and search.

这是一道字典树基本题。题设上非常简单直接,但是它好的地方是搜索时带了一个 . ,扩大了搜索范围。

421 中我们也用到字典树解决问题,所以该数据结构可能很常见。

var WordDictionary = function() { this.Trie = {} }; /** * @param {string} word * @return {void} */ WordDictionary.prototype.addWord = function(word) { let p = this.Trie for (let i=0; i<word.length; i++) { const crt = word[i] if (!p[crt]) { p[crt] = {} } p = p[crt] } p.EOW = true }; /** * @param {string} word * @return {boolean} */ WordDictionary.prototype.search = function(word, i=0, tree) { if (i === word.length) return tree.EOW === true let p = tree || this.Trie let crt = word[i] if (crt === '.') { for (let t of Object.values(p)) { if (this.search(word, i+1, t)) return true } return false } else { if (!p[crt]) return false return this.search(word, i+1, p[crt]) } }; /** * Your WordDictionary object will be instantiated and called as such: * var obj = new WordDictionary() * obj.addWord(word) * var param_2 = obj.search(word) */