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
}
相关推荐
浅念-3 小时前
LeetCode 回溯算法题——综合练习
数据结构·c++·算法·leetcode·职场和发展·深度优先·dfs
圣保罗的大教堂4 小时前
leetcode 61. 旋转链表 中等
leetcode
珊瑚里的鱼7 小时前
leetcode42雨水
算法·leetcode
过期动态8 小时前
【LeetCode 热题 100】字母异位分组
java·算法·leetcode·职场和发展·哈希算法
mumu_wangwei9 小时前
【QFS】Golang自研的QFS分布式文件系统,QFS文件系统使用
开发语言·后端·golang
alphaTao11 小时前
LeetCode 每日一题 2026/5/18-2026/5/24
python·leetcode
过期动态11 小时前
【LeetCode 热题 100】两数之和— 暴力法与哈希表法详解
java·数据结构·算法·leetcode·散列表
codeejun12 小时前
每日一Go-66、K8s 蓝绿发布 & 金丝雀发布实战:Service 切流量 + Ingress 灰度一次讲透
开发语言·golang·kubernetes
青春喂了后端13 小时前
Go Sidecar Repository 并发锁改造:让并发请求安全地进入 Git 仓库层
git·安全·golang
sheeta199813 小时前
LeetCode 每日一题笔记 日期:2026.05.24 题目:1340. 跳跃游戏 V
笔记·leetcode·游戏