字典树实现_数据结构与算法之字典树(Golang实现)

本文介绍了字典树(Trie树)的算法原理,包括其利用字符串公共前缀节省空间的设计思路,以及在构建和查询上的时间复杂度。详细阐述了算法步骤,如根节点的设定、节点间的连接方式。同时,分析了字典树的优缺点,指出其在内存消耗和查询效率上的特点,特别适合自动补全等应用。
摘要由CSDN通过智能技术生成

59d55de782d479fe48557298d830c718.gif

1. 字典树

算法描述:trie树的本质,就是利用字符串之间的公共前缀,将重复的前缀合并在一起。时间复杂度:构建O(n),查询O(k)

1.1.1. 算法步骤

  • 根节点/ 什么都不表示

  • 做一个字典比如a-z 字母表

  • 没一个节点包含这26个字母的字典表,每个位置保存下个节点的指针。

1.1.2. 算法分析

缺点:

  • trie树比较消耗内存:因为他没一层都保存一个字典表,就算这层的节点只有一个也要有一组表

  • 使用的是指针类型,内存不连续对存储不友好,性能打折扣 优点:

  • 查询效率比较高,对于一些范围较小的或者内存不敏感的应用可以使用

  • 特别适用自动补全类应用

package main

import "fmt"

type TrieNode struct {
value int
dictionary [26]*TrieNode
}

type TrieTree struct {
root *TrieNode
}

func main() {
tree := createTree()
//fmt.Println(tree)
flag := tree.findWord("her")
fmt.Println(flag)
flag = tree.findWord("x")
fmt.Println(flag)
}

func createTree() TrieTree {
arrList := []string{"how", "hi", "her", "hello", "so", "see"}
myTree := TrieTree{}
//添加跟节点
myTree.root = &TrieNode{}
for _, value := range arrList {
myTree.addWord(value)
}
return myTree
}
func (t *TrieTree) addWord(word string) {
fmt.Println(word)
nowNode := t.root
a := int('a')
var char int
for i := 0; i < len(word); i++ {
char = int(word[i])
if nowNode.dictionary[char-a] != nil {
nowNode = nowNode.dictionary[char-a]
continue
} else {
newNode := &TrieNode{}
nowNode.dictionary[char-a] = newNode
nowNode = newNode
continue
}
}
}

func (t *TrieTree) findWord(word string) int {
nowNode := t.root
a := int('a')
var char int
for i := 0; i < len(word); i++ {
char = int(word[i])
if nowNode.dictionary[char-a] != nil {
return 0
} else {
nowNode = nowNode.dictionary[char-a]
}
if i == len(word)-1 {
return 1
}
}
return 0
}
4658d42444720b9ce3968e1b819f775a.png - End - 9cb0feff28de98f39eb006c6bc9e652b.png

好文点赞收藏

676888b2f9cef5d09c11b799c88acd7e.png676888b2f9cef5d09c11b799c88acd7e.png676888b2f9cef5d09c11b799c88acd7e.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值