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'));
    
    
  • 相关阅读:
    更好的抽屉效果(ios)
    系统拍照动画
    UITabBarController详解
    touch事件分发
    iOS UWebView详解
    iOS 监听声音按键
    webservice偶尔报黄页,解决方案
    FastReport脚本把数据绑定到文本控件上
    [转]js版的md5()
    JQuery中$.ajax()方法参数详解
  • 原文地址:https://www.cnblogs.com/pluslius/p/10813557.html
Copyright © 2011-2022 走看看