简单记录一下trie树

在计算机科学中,trie,又称前缀树或字典树,是一种有序树,用于保存关联数组,其中的键通常是字符串。与二叉查找树不同,键不是直接保存在节点中,而是由节点在树中的位置决定。一个节点的所有子孙都有相同的前缀,也就是这个节点对应的字符串,而根节点对应空字符串。一般情况下,不是所有的节点都有对应的值,只有叶子节点和部分内部节点所对应的键才有相关的值。
trie.go

package trie


import (
   "unicode/utf8"
)


type Trie struct {
   isWord   bool
   children [1024*1024]*Trie
}


/** Initialize your data structure here. */
func NewTrie() *Trie {
   return &Trie{}
}


/** Inserts a word into the trie. */
func (this *Trie) Insert(word string) {
   cur := this
   for i, c := range []rune(word) {
      n := c
      if cur.children[n] == nil {
         cur.children[n] = NewTrie()
      }
      cur = cur.children[n]
      if i == utf8.RuneCountInString(word)-1 {
         cur.isWord = true
      }
   }
}


/** Returns if the word is in the trie. */
func (this *Trie) Search(word string) bool {
   cur := this
   for _, c := range word {
      n := c
      if cur.children[n] == nil {
         return false
      }
      cur = cur.children[n]
   }
   return cur.isWord
}


/** Returns if there is any word in the trie that starts with the given prefix. */
func (this *Trie) StartsWith(prefix string) bool {
   cur := this
   for _, c := range []rune(prefix) {
      n := c
      if cur.children[n] == nil {
         return false
      }
      cur = cur.children[n]
   }
   return true
}

trie_test.go

package trie


import (
   "testing"
)


func TestRead(t *testing.T) {
   s := NewTrie()
   s.Insert("你好")
   s.Insert("哈哈")
   s.Insert("123")
   s.Insert("abc")
   s.Insert("好人")
   println(s.Search("你好"))
   println(s.Search("abc"))
   println(s.Search("你是好人")) // false
}

参考文章:https://blog.csdn.net/weixin_39778570/article/details/81990417

posted @ 2021-03-29 11:31  lisq  阅读(50)  评论(0编辑  收藏  举报