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
}
相关推荐
一匹电信狗4 小时前
【C++】异常详解(万字解读)
服务器·c++·算法·leetcode·小程序·stl·visual studio
Python私教5 小时前
从“Hello World”到“高并发中间件”:Go 语言 2025 系统学习路线图
学习·中间件·golang
墨染点香5 小时前
LeetCode 刷题【43. 字符串相乘】
算法·leetcode·职场和发展
Keying,,,,5 小时前
力扣hot100 | 矩阵 | 73. 矩阵置零、54. 螺旋矩阵、48. 旋转图像、240. 搜索二维矩阵 II
python·算法·leetcode·矩阵
_不会dp不改名_7 小时前
leetcode_42 接雨水
算法·leetcode·职场和发展
code小毛孩10 小时前
leetcode hot100数组:缺失的第一个正数
数据结构·算法·leetcode
快去睡觉~20 小时前
力扣400:第N位数字
数据结构·算法·leetcode
gzzeason21 小时前
LeetCode Hot100:递归穿透值传递问题
算法·leetcode·职场和发展
光爷不秃1 天前
Go语言中安全停止Goroutine的三种方法及设计哲学
开发语言·安全·golang
qq_513970441 天前
力扣 hot100 Day74
数据结构·算法·leetcode