leetcode 211题

Posted by franki on September 11, 2021

leetcode 211题 添加与搜索单词 - 数据结构设计

请你设计一个数据结构,支持 添加新单词 和 查找字符串是否与任何先前添加的字符串匹配 。

实现词典类 WordDictionary :

WordDictionary() 初始化词典对象 void addWord(word) 将 word 添加到数据结构中,之后可以对它进行匹配 bool search(word) 如果数据结构中存在字符串与 word 匹配,则返回 true ;否则,返回  false 。word 中可能包含一些 ‘.’ ,每个 . 都可以表示任何一个字母。

示例 1:

输入:
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
输出:
[null,null,null,null,false,true,true,true]

解释:
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

思路

bfs

代码

var WordDictionary = function() {
    this.parent = {};
};

/** 
 * @param {string} word
 * @return {void}
 */
WordDictionary.prototype.addWord = function(word) {
    let curr = this.parent;
    for (const w of word) {
        if (curr[w]) {
            curr = curr[w];
        } else {
            curr[w] = {};
            curr = curr[w];
        }
    }
    curr.isWord = true;
};

/** 
 * @param {string} word
 * @return {boolean}
 */
WordDictionary.prototype.search = function(word, parent = this.parent) {
    let curr = parent;
    for (let i=0; i<word.length; i++) {
        const w = word[i];
        if (w === '.') {
            let isMatched = false;
            for (const key in curr) {
                if (this.search(word.slice(i+1), curr[key])) {
                    isMatched = true;
                }
            }
            return isMatched;
        } else if (!curr[w]) {
            return false;
        }
        curr = curr[w];
    }
    return !!curr.isWord;
};

/**
 * Your WordDictionary object will be instantiated and called as such:
 * var obj = new WordDictionary()
 * obj.addWord(word)
 * var param_2 = obj.search(word)
 */

复杂度分析

  • 时间复杂度:O(N)
  • 空间复杂度:O(N)