zoukankan      html  css  js  c++  java
  • Trie树

    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'));
    
    
  • 相关阅读:
    在线api文档
    Android Studio 快捷键
    AtomicBoolean运用
    ubuntu下Pycharm安装及配置
    Pycharm Professional Edition 激活码(license)
    opengl中对glOrtho()函数的理解
    附加作业
    个人最终总结
    mysql
    创建数据库
  • 原文地址:https://www.cnblogs.com/pluslius/p/10813557.html
Copyright © 2011-2022 走看看