Skip to content

实现trie前缀树

问题

答案

看不懂啊看不懂

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

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

/** 
 * @param {string} word
 * @return {boolean}
 */
Trie.prototype.search = function(word) {
    let node=this.children;
    for(const ch of word){
        if(!node[ch]){
            return false;
        }
        node=node[ch];
    }
    return node!==undefined&&node.isEnd!==undefined;
};

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

/** 
 * 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)
 */

扩展

字典树 树形结构 又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。