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
}
相关推荐
喵了几个咪2 小时前
GoWind Admin 拆解:智能问数——从一句自然语言到一张可信图表
ai·golang·llm·智能问数·gowind
catchadmin3 小时前
Laravel Go 高性能全栈框架发布
golang·php·laravel
小白的高手之路3 小时前
【LeetCode 热题 100】206. 反转链表|链表、迭代、递归(Python)
笔记·python·算法·leetcode·链表·职场和发展·力扣
16月6日-晴4 小时前
122. 买卖股票的最佳时机 II【贪心】
算法·leetcode
我不会起名字3225 小时前
Go 泛型与反射边界:编译膨胀、接口装箱与热路径的 4 个取舍
golang·go·反射·泛型·后端架构
小白的高手之路6 小时前
【【LeetCode 热题 100】160. 相交链表|链表、哈希表、双指针(Python)
python·算法·leetcode·链表·力扣·散列表
SEO_juper7 小时前
Go 全站 H1 批量检查工具:并发抓取,找出 H1 数量不对的页面
开发语言·后端·golang
灯澜忆梦8 小时前
拓扑排序(Kahn BFS)| LeetCode 210 课程表 II
算法·leetcode·排序算法·宽度优先
xcLeigh9 小时前
Go入门:逻辑运算符与短路求值机制
android·java·golang·go·教程
Nuanyt9 小时前
LeetCode Hot 100 贪心算法专题 121 / 55 / 45 / 763 (Java)
java·算法·leetcode·贪心算法·dp