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
}
相关推荐
楼田莉子22 分钟前
C++算法专题学习——分治
数据结构·c++·学习·算法·leetcode·排序算法
He19550132 分钟前
Go初级之十:错误处理与程序健壮性
开发语言·python·golang
一支鱼39 分钟前
leetcode常用解题方案总结
前端·算法·leetcode
吃着火锅x唱着歌1 小时前
LeetCode 1537.最大得分
算法·leetcode·职场和发展
不会吃萝卜的兔子2 小时前
go webrtc - 1 go基本概念
开发语言·golang·webrtc
j_xxx404_4 小时前
数据结构:栈和队列力扣算法题
c语言·数据结构·算法·leetcode·链表
Lris-KK4 小时前
【Leetcode】高频SQL基础题--180.连续出现的数字
sql·leetcode
珍珠是蚌的眼泪5 小时前
LeetCode_位运算
leetcode·位运算·异或·韩明距离·数字的补数
野犬寒鸦5 小时前
力扣hot100:旋转图像(48)(详细图解以及核心思路剖析)
java·数据结构·后端·算法·leetcode
墨染点香5 小时前
LeetCode 刷题【61. 旋转链表】
算法·leetcode·职场和发展