Leetcode刷题(第208)——实现 Trie (前缀树)

x33g5p2x  于2022-03-15 转载在 其他  
字(1.4k)|赞(0)|评价(0)|浏览(149)

一、题目

二、示例

输入
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
输出
[null, null, true, false, true, null, true]

解释
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple");   // 返回 True
trie.search("app");     // 返回 False
trie.startsWith("app"); // 返回 True
trie.insert("app");
trie.search("app");     // 返回 True

三、思路

如上图所示,可以实现树,当插入单词的时候,遍历每一个字母,如果该字母存在,则继续向下遍历,如果 不存在就以该字母的为key赋值为一个对象,当插入完全后,则给该对象设置一个值为isEnd = true
四、代码

var Trie = function () {
    this.root = {}
};

/** 
 * @param {string} word
 * @return {void}
 */
Trie.prototype.insert = function (word) {
    let node = this.root
    for (let item of word) {
        if (!node[item]) {
            node[item] = {}
        }
        node = node[item]
    }
    node.isEnd = true
};

/** 
 * @param {string} word
 * @return {boolean}
 */
Trie.prototype.search = function (word) {
    let node = this.root
    for (let item of word) {
        if (!node[item]) {
            return false
        }
        node = node[item]
    }
    return node.isEnd ? true : false
};

/** 
 * @param {string} prefix
 * @return {boolean}
 */
Trie.prototype.startsWith = function (prefix) {
    let node = this.root
    for(let item of prefix) {
        if(!node[item]) {
            return false
        }
        node = node[item]
    }
    return true
};

/**
 * Your Trie object will be instantiated and called as such:
 * var obj = new Trie()
 * obj.insert(word)
 * var param_2 = obj.search(word)
 * var param_3 = obj.startsWith(prefix)
 */

五、总结

相关文章

微信公众号

最新文章

更多