wengzc / leetcode

Record the leetcode
1 stars 0 forks source link

208. 实现 Trie (前缀树) #168

Open wengzc opened 4 years ago

wengzc commented 4 years ago

实现一个 Trie (前缀树),包含 insertsearch, 和 startsWith 这三个操作。

示例:

说明:

题目链接:https://leetcode-cn.com/problems/implement-trie-prefix-tree

wengzc commented 4 years ago

Trie (前缀树)知识学习:链接

/**
 * Initialize your data structure here.
 */
var Trie = function () {
    this.root = {}
};

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

/**
 * Returns if the word is in the trie. 
 * @param {string} word
 * @return {boolean}
 */
Trie.prototype.search = function (word) {
    let node = this.root
    for (let c of word) {
        node = node[c]
        if (!node) return false
    }
    return !!node.isEnd
};

/**
 * Returns if there is any word in the trie that starts with the given prefix. 
 * @param {string} prefix
 * @return {boolean}
 */
Trie.prototype.startsWith = function (prefix) {
    let node = this.root
    for (let c of prefix) {
        node = node[c]
        if (!node) {
            return false
        }
    }
    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)
 */