字典树Trie模板

Python版本
class Trie:
    def __init__(self):
        self.children = defaultdict(Trie)
        self.word = ""
        self.is_word = False
    def insert(self, word):
        cur = self
        for w in word:
            cur = cur.children[w]
        cur.is_word = True
        cur.word = word
    def search(self, word):
        cur = self
        for w in word:
            if w not in cur.children:
                return False
            cur = cur.children[w]
        return cur.is_word

下面是Golang实现

Golang版本
package main

import (
	"fmt"
	"strconv"
)

type Trie struct {
	Child map[interface{}]*Trie
	IsEnd bool
}

func Constructor() Trie {
	return Trie{}
}

func (this *Trie) Insert(word string) {
	t := this
	for _, v := range word {
		if t.Child == nil {
			t.Child = make(map[interface{}]*Trie)
		}
		if _, ok := t.Child[v]; !ok {
			t.Child[v] = &Trie{}
		}
		t = t.Child[v]
	}
	t.IsEnd = true
}

func (this *Trie) Search(word string) bool {
	t := this
	for index, v := range word {
		if t.Child == nil {
			return false
		}
		if _, ok := t.Child[v]; !ok {
			return false
		}
		t = t.Child[v]
		if index == len(word)-1 && !t.IsEnd {
			return false
		}
	}
	return true
}

func (this *Trie) StartsWith(prefix string) bool {
	t := this
	for _, v := range prefix {
		if t.Child == nil {
			return false
		}
		if _, ok := t.Child[v]; !ok {
			return false
		}
		t = t.Child[v]
	}
	return true
}

func main() {
	word := "he;;p"
	obj := Constructor()
	obj.Insert(word)
	param_2 := obj.Search(word)
	fmt.Println(param_2)
	prefix := "he;"
	param_3 := obj.StartsWith(prefix)
	fmt.Println(param_3)
	binnum := fmt.Sprintf("%.3f", 7.12)
	f, _ := strconv.ParseFloat(binnum, 64)
	fmt.Println(f)

	mp := make(map[interface{}]interface{})
	mp[10] = 10
	mp['a'] = 10
	mp["ASD"] = func() bool { return false }

	fmt.Printf("%T", mp["ASD"])

}

posted @   Notomato  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示