当前位置: 移动技术网 > IT编程>开发语言>JavaScript > Trie树

Trie树

2019年05月06日  | 移动技术网IT编程  | 我要评论
class trienode {
    constructor(data){
        this.data = data
        this.children = new array(26)
        this.isendingchar = false
        this.text = ''
    }
}

class trietree {
    constructor(){
        this.root = new trienode('/')
    }
    insert(text){
        let currentnode = this.root
        for(let char of text){
            let index = char.charcodeat() - 'a'.charcodeat()
            if(!currentnode.children[index]){
                currentnode.children[index] = new trienode(char)
            }
            currentnode = currentnode.children[index] 
        }
        currentnode.isendingchar = true
        currentnode.text = text
    }
    find(text){
        let currentnode = this.root
        for(let char of text){
            let index = char.charcodeat() - 'a'.charcodeat()
            if(currentnode.children[index]){
                currentnode = currentnode.children[index]
            } else {
               return {
                input:text,
                result: false
               }
            }
        }
        return {
            input:currentnode.text,
            result:currentnode.isendingchar
        }
    }
}

let tree = new trietree()
let strs = ["how", "hi", "her", "hello", "so", "see"];
for(let str of strs) {
    tree.insert(str);
}

for(let str of strs) {
    console.log(tree.find(str));
}

console.log(tree.find('world'));

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网