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
}
相关推荐
java_nnnn11 小时前
LeetCode刷题滑动窗口(串联所有单词的子串+最小覆盖的子串)Java
算法·leetcode·职场和发展
Navigator_Z12 小时前
LeetCode //C - 1301. Number of Paths with Max Score
c语言·算法·leetcode
Nuanyt14 小时前
LeetCode Hot100 刷题笔记 · 普通数组专题
java·笔记·算法·leetcode
飞鸟真人15 小时前
IM网关系列(九)单账号流量统计:滑动窗口桶方案设计与Go实现
后端·golang
春弦_16 小时前
LeetCode Hot 100 刷题笔记
笔记·leetcode·哈希算法
紧跟先前的步伐18 小时前
Go AI Agent 实战 11|请求结构、响应结构与 JSON 解析
人工智能·ai·golang·json
凯瑟琳.奥古斯特19 小时前
力扣1015C++解法技巧
c++·算法·leetcode·链表·职场和发展
文丑颜不良啊19 小时前
LeetCode626~650题目解析
java·leetcode
利威尔xu20 小时前
Go IM 源码实战(2):WebSocket 握手 11 步,少 1 个参数连不上
后端·websocket·微服务·面试·golang
文丑颜不良啊20 小时前
LeetCode601~625题目解析
java·leetcode