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
}
相关推荐
qq_5139704424 分钟前
力扣 hot100 Day56
算法·leetcode
Hello.Reader3 小时前
Go-Elasticsearch v9 安装与版本兼容性
elasticsearch·golang·jenkins
爱喝矿泉水的猛男3 小时前
非定长滑动窗口(持续更新)
算法·leetcode·职场和发展
YuTaoShao4 小时前
【LeetCode 热题 100】131. 分割回文串——回溯
java·算法·leetcode·深度优先
五岁小孩4 小时前
实操使用 go pprof 对生产环境进行性能分析(问题定位及代码优化)
性能优化·golang·pprof
大锦终6 小时前
【算法】前缀和经典例题
算法·leetcode
cccc来财7 小时前
Java实现大根堆与小根堆详解
数据结构·算法·leetcode
恣艺8 小时前
LeetCode 854:相似度为 K 的字符串
android·算法·leetcode
一杯科技拿铁8 小时前
Go 的时间包:理解单调时间与挂钟时间
开发语言·后端·golang
刚入坑的新人编程9 小时前
暑期算法训练.9
数据结构·c++·算法·leetcode·面试·排序算法