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
}
相关推荐
Wang's Blog6 小时前
Go-Zero 项目开发22:用户群聊功能的实现与完善
开发语言·golang
Wang's Blog9 小时前
Go-Zero项目开发24: 基于Bitmap实现群聊消息已读未读
开发语言·后端·golang
keep intensify11 小时前
最长有效括号
算法·leetcode·动态规划
CoderYanger11 小时前
A.每日一题:1979. 找出数组的最大公约数
java·程序人生·算法·leetcode·面试·职场和发展·学习方法
布朗克16813 小时前
Go 入门到精通-33-unsafe 与 CGO
开发语言·后端·golang·unsafe·cgo
ttwuai14 小时前
AI 生成后台删除按钮后,MySQL 软删除和唯一索引怎么验
数据库·mysql·golang
INGNIGHT16 小时前
528.按权重随机选择(前缀和&二分法)加权负载均衡
算法·leetcode
runafterhit16 小时前
python基础语法命令(C程序员刷leetcode)
c语言·python·leetcode
青山木16 小时前
Hot 100 --- 全排列
java·数据结构·算法·leetcode·深度优先
Wang's Blog17 小时前
Go-Zero 项目开发19:基于 Kafka 的异步消息存储与转发实战
golang·kafka