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
}
相关推荐
小欣加油13 分钟前
leetcode 329 矩阵中的最长递增路径
c++·算法·leetcode·矩阵·深度优先·剪枝
Emilia486.16 分钟前
【Leetcode&nowcode&数据结构】单链表的应用(初阶)
c语言·数据结构·算法·leetcode
千码君201618 分钟前
Go语言:记录一下Go语言系统学习的第一天
java·开发语言·学习·golang·gin·并发编程·编译语言
仰泳的熊猫1 小时前
LeetCode:700. 二叉搜索树中的搜索
数据结构·c++·算法·leetcode
代码充电宝1 小时前
LeetCode 算法题【中等】189. 轮转数组
java·算法·leetcode·职场和发展·数组
微笑尅乐2 小时前
从递归到迭代吃透树的层次——力扣104.二叉树的最大深度
算法·leetcode·职场和发展
im_AMBER2 小时前
Leetcode 28
算法·leetcode
And_Ii2 小时前
LeetCode 3350. 检测相邻递增子数组 II
数据结构·算法·leetcode
冷月葬花~3 小时前
day24
数据结构·算法·leetcode