javascript实现字典树trie

Trie Tree 简介

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

性质

它有3个基本性质:

  1. 根节点不包含字符,除根节点外每一个节点都只包含一个字符。
  2. 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
  3. 每个节点的所有子节点包含的字符都不相同。

Trie Tree 结构

 
Trie Tree
//javascript实现字典树trie,简单的实现下
class TrieNode {
    constructor(value){
        this.value = value; //value为单个字符
        this.num=1;
        this.son=[];
        this.isEnd=false;
    }
    findNode(value){
        for(let i=0;i<this.son.length;i++){
            const node=this.son[i]
            if(node.value == value){
                return node;
            }
        }
        return null;
    }
}
class Trie {
    constructor(){
        this.root=new TrieNode(null);
        this.size=1;//一开始的时候只有根节点这一个节点
    }
    insert(str){
        let node=this.root;
        for(let c of str){

            let snode = node.findNode(c);
            if(snode==null){
                snode=new TrieNode(c)
                node.son.push(snode);
            }else{
                snode.num++;//有N个字符串经过它
            }
            node=snode;

        }
        //如果当前的node已经是一个word,则不需要添加
        if (!node.isEnd) {
            this.size++;
            node.isEnd = true;
        }
    }
    has(str){
        let node=this.root;
        for(let c of str){
            const snode=node.findNode(c)
            if(snode){
                node=snode;
            }else{
                return false;
            }
        }
        return node.isEnd;
    }
}

//demo
const nt=new Trie()
nt.insert('name');
nt.insert('word');
nt.insert('happy');
nt.insert('trie');

// console.log(nt.root['d'])
console.log(nt.has('has'))
console.log(nt.has('trie'))
console.log(nt.has('word'))

  

猜你喜欢

转载自www.cnblogs.com/caoke/p/10828895.html