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
}
相关推荐
烧瓶里的西瓜皮20 分钟前
Go语言从零构建SQL数据库引擎(2)
数据库·sql·golang
亓才孓2 小时前
[leetcode]树的操作
算法·leetcode·职场和发展
loser~曹3 小时前
基于快速排序解决 leetcode hot215 查找数组中第k大的数字
数据结构·算法·leetcode
Dream it possible!3 小时前
LeetCode 热题 100_打家劫舍(83_198_中等_C++)(动态规划)
c++·算法·leetcode·动态规划
SylviaW083 小时前
python-leetcode 62.搜索插入位置
数据结构·算法·leetcode
赴前尘3 小时前
Go+Gin实现安全多文件上传:带MD5校验的完整解决方案
安全·golang·gin
Joe_Wang55 小时前
[图论]拓扑排序
数据结构·c++·算法·leetcode·图论·拓扑排序
梭七y5 小时前
【力扣hot100题】(033)合并K个升序链表
算法·leetcode·链表
月亮被咬碎成星星6 小时前
LeetCode[383]赎金信
算法·leetcode