Golang | Leetcode Golang题解之第208题实现Trie前缀树

题目:

题解:

Go 复制代码
type Trie struct {
    children [26]*Trie
    isEnd    bool
}

func Constructor() Trie {
    return Trie{}
}

func (t *Trie) Insert(word string) {
    node := t
    for _, ch := range word {
        ch -= 'a'
        if node.children[ch] == nil {
            node.children[ch] = &Trie{}
        }
        node = node.children[ch]
    }
    node.isEnd = true
}

func (t *Trie) SearchPrefix(prefix string) *Trie {
    node := t
    for _, ch := range prefix {
        ch -= 'a'
        if node.children[ch] == nil {
            return nil
        }
        node = node.children[ch]
    }
    return node
}

func (t *Trie) Search(word string) bool {
    node := t.SearchPrefix(word)
    return node != nil && node.isEnd
}

func (t *Trie) StartsWith(prefix string) bool {
    return t.SearchPrefix(prefix) != nil
}
相关推荐
凯瑟琳.奥古斯特27 分钟前
力扣1008:前序重建BST
开发语言·c++·算法·leetcode·职场和发展
aqiu1111111 小时前
【算法日记 13】LeetCode 49. 字母异位词分组:哈希表的进阶“降维打击”
算法·leetcode·散列表
名字还没想好☜3 小时前
Go 并发实战:用 channel 实现 worker pool
java·数据库·后端·golang·go
人道领域3 小时前
【LeetCode刷题日记】贪心算法理论与实战:455.分发饼干最优解
java·开发语言·数据结构·算法·leetcode·贪心算法
布朗克1684 小时前
Go 入门到精通-09-复合类型之Map
开发语言·后端·golang·map
极***技4 小时前
2026云原生核心!Go高并发限流实战,从原理到落地
开发语言·云原生·golang
王老师青少年编程12 小时前
2026年6月GESP真题及题解(C++一级):交税
c++·题解·真题·gesp·一级·2026年6月·交税
开发小程序的之朴15 小时前
认识安企CMS-安装安企CMS的环境要求
nginx·golang·系统架构
北冥you鱼17 小时前
abigen 最佳实践:从入门到精通,高效生成 Go 语言合约绑定
开发语言·golang·区块链
北冥you鱼20 小时前
Go 语言读取链上数据:从基础到实战
开发语言·后端·golang