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
}
相关推荐
语戚38 分钟前
力扣 51. N 皇后:基础回溯、布尔数组优化、位运算全解(Java 实现)
java·算法·leetcode·力扣·剪枝·回溯·位运算
py有趣1 小时前
力扣热门100题之螺旋矩阵
算法·leetcode
Wenweno0o1 小时前
Eino - 从0到1跑通大模型调用
golang·大模型·智能体·eino
人道领域1 小时前
【LeetCode刷题日记】383 赎金信
算法·leetcode·职场和发展
旖-旎1 小时前
哈希表(存在重复元素)(3)
数据结构·c++·学习·算法·leetcode·散列表
Tisfy2 小时前
LeetCode 3740.三个相等元素之间的最小距离 I:今日先暴力,“明日“再哈希
算法·leetcode·哈希算法·题解·模拟·遍历·暴力
不会写DN2 小时前
IPv4 与 IPv6 的核心区别
计算机网络·面试·golang
我真不是小鱼2 小时前
cpp刷题打卡记录27——无重复字符的最长子串 & 找到字符串中所有字母的异位词
数据结构·c++·算法·leetcode
We་ct2 小时前
LeetCode 69. x 的平方根:两种解法详解
前端·javascript·算法·leetcode·typescript·平方
Flandern11113 小时前
Go程序员学习AI大模型项目实战02:给 AI 装上“大脑”:从配置解包到流式生成的深度拆解
人工智能·后端·python·学习·golang