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
}
相关推荐
青山木26 分钟前
Hot 100 --- 缺失的第一个正数
算法·leetcode·哈希算法
农民小飞侠26 分钟前
[leetcode] 165. Compare Version Numbers
java·算法·leetcode
java_cj2 小时前
从kubectl学Visitor模式:如何优雅处理多态数据结构的遍历
云原生·golang·k8s·访问者模式
Tisfy3 小时前
LeetCode 2095.删除链表的中间节点:两次遍历 / 一次遍历(快慢指针)
算法·leetcode·链表·题解·双指针
凌波粒4 小时前
LeetCode--131.分割回文串(回溯算法)
算法·leetcode·职场和发展
何以解忧,唯有..4 小时前
Go语言类型转换详解:从基础到进阶实践
开发语言·后端·golang
何以解忧,唯有..4 小时前
Go 语言指针类型详解:从基础到实战
开发语言·后端·golang
迷茫运维路4 小时前
Casbin学习教程
golang·casbin
techdashen4 小时前
Go 语言仓库 Top 100 贡献者分析报告
开发语言·后端·golang
何以解忧,唯有..4 小时前
Go 语言变量命名规范详解
开发语言·后端·golang