zoukankan      html  css  js  c++  java
  • trie树

    golang code:

    package main
    
    import (
    	"fmt"
    )
    
    // trie,根节点没有字符,然后每层一个字符, 前缀相同的是同一路径
    // 如:   test, team 有相同前缀 te, warm, warn 有相同前缀war
    //          __ root__
    //         /         
    //        t           w
    //       /           /
    //      e           a
    //     /          /
    //    s   a       r
    //   /          / 
    //  t	    m   m   n
    //
    // 这个例子是通过 字符串,查找字符串对应的值
    
    type Node struct {
    	Children map[byte]*Node // 子结点
    	Priority int
    }
    
    func NewNode() *Node {
    	return &Node{make(map[byte]*Node), 0}
    }
    
    type Trie struct {
    	Root *Node
    }
    
    func NewTrie() *Trie {
    	root := NewNode()
    	return &Trie{root}
    }
    
    func (t *Trie) Insert(str string, priority int) {
    	bytes := []byte(str)
    	current := t.Root
    	for i := 0; i < len(bytes); i++ {
    		char := bytes[i]
    		if node := current.Children[char]; node != nil {
    			current = node
    		} else {
    			newnode := NewNode()
    			current.Children[char] = newnode
    			current = newnode
    		}
    	}
    	current.Priority = priority
    }
    
    // 根据str, 查找其对应的priority
    func (t *Trie) Find(str string) int {
    	bytes := []byte(str)
    	current := t.Root
    	fmt.Print("find ")
    	for i := 0; i < len(bytes); i++ {
    		char := bytes[i]
    		fmt.Print(string(char))
    		if node := current.Children[char]; node == nil {
    			fmt.Println(": not found")
    			return -1
    		} else {
    			current = node
    		}
    	}
    	priority := current.Priority
    	fmt.Println(", priority: ", priority)
    	return priority
    }
    
    func main() {
    	words := []string{"test", "team", "space", "work", "missing", "illegal", "go", "golang"}
    	priority := []int{4, 5, 6, 7, 8, 9, 10, 11}
    
    	trie := NewTrie()
    
    	// 建trie树
    	for i := 0; i < len(words); i++ {
    		trie.Insert(words[i], priority[i])
    	}
    
    	// 查找
    	trie.Find("test")
    	trie.Find("team")
    	trie.Find("space")
    	trie.Find("work")
    	trie.Find("missing")
    	trie.Find("illegal")
    	trie.Find("go")
    	trie.Find("golang")
    } 
    // 输出
    
    find test, priority: 4
    
    find team, priority: 5
    
    find space, priority: 6
    
    find work, priority: 7
    
    find missing, priority: 8
    
    find illegal, priority: 9
    
    find go, priority: 10
    
    find golang, priority: 11
    
    成功: 进程退出代码 0.
  • 相关阅读:
    Oracle 10g R2 Transparent Data Encryption 透明数据加密
    Spark之Task原理分析
    一个Spark job的生命历程
    Spark调优秘诀——超详细
    NLP文本相似度(TF-IDF)
    Spark 参数配置的几种方法
    Spark提交应用程序之Spark-Submit分析
    spark_flume_mysql 整合
    Spark Programming Guide《翻译》
    windows下Idea结合maven开发spark和本地调试
  • 原文地址:https://www.cnblogs.com/bear129/p/9050955.html
Copyright © 2011-2022 走看看