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
}
相关推荐
刘铸纬7 小时前
Golang中defer和return顺序
开发语言·后端·golang
DogDaoDao8 小时前
LeetCode 算法:二叉树中的最大路径和 c++
c++·算法·leetcode·二叉树·二叉树路径
可惜我是水瓶座__8 小时前
【LeetCode】螺旋矩阵
算法·leetcode·矩阵
观鉴词recommend10 小时前
【c++刷题笔记-贪心】day30:56. 合并区间 、 738.单调递增的数字
c++·笔记·算法·leetcode
音符犹如代码12 小时前
3101.力扣每日一题7/6 Java(接近100%解法)
java·数据结构·算法·leetcode
观鉴词recommend13 小时前
【c++刷题笔记-数组】day29:452. 用最少数量的箭引爆气球、 435. 无重叠区间 、 763.划分字母区间
c++·算法·leetcode
liupenglove14 小时前
golang线程池ants-实现架构
开发语言·后端·golang·多线程
嘿,请叫我小哥14 小时前
定个小目标之刷LeetCode热题(41)
算法·leetcode·职场和发展
菜鸟开卷19 小时前
Go 语言入门(一)
开发语言·后端·golang
__AtYou__20 小时前
Golang | Leetcode Golang题解之第220题存在重复元素III
leetcode·golang·题解