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
}
相关推荐
緈福的街口8 小时前
【leetcode】2900. 最长相邻不相等子序列 I
算法·leetcode·职场和发展
进击的小白菜8 小时前
LeetCode 153. 寻找旋转排序数组中的最小值:二分查找法详解及高频疑问解析
数据结构·算法·leetcode
Chandler2410 小时前
Go语言 GORM框架 使用指南
开发语言·后端·golang·orm
wktomo11 小时前
GO语言学习(二)
学习·golang
緈福的街口11 小时前
【leetcode】144. 二叉树的前序遍历
算法·leetcode
你怎么知道我是队长11 小时前
Go语言语法---输入控制
golang
蚂蚁在飞-11 小时前
Golang基础知识—cond
开发语言·后端·golang
李迟12 小时前
Golang实践录:在go中使用curl实现https请求
开发语言·golang·https
Dream it possible!13 小时前
LeetCode 热题 100_寻找重复数(100_287_中等_C++)(技巧)(暴力解法;哈希集合;二分查找)
c++·leetcode·哈希算法
BUG制造机.13 小时前
Go 语言的 GMP 模型
golang