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
}
相关推荐
a187927218316 分钟前
【算法】动态规划第五篇:区间 DP——从“看什么都像背包“到“最后戳谁“
算法·leetcode·动态规划·dp·区间·区间dp·算法讲解
rannn_1111 小时前
【力扣hot100】多维动态规划|62、64、5、1143、72
算法·leetcode·动态规划
计科杨某人2 小时前
简单算法题(基础入门题)
c++·算法·题解·入门·基础算法
find1star11 小时前
LeetCode 141:环形链表
java·算法·leetcode·链表
LB211211 小时前
力扣160 21 86
算法·leetcode·职场和发展
王的宝库11 小时前
Go 项目结构:从单文件到标准工程布局
开发语言·后端·golang
花酒锄作田12 小时前
Go - Gin中使用sessions
golang
a1879272183112 小时前
【算法】动态规划第二篇:双序列 DP 三课——继承、计步与断链
算法·leetcode·动态规划·dp·回溯·暴力·算法讲解
不甘先生17 小时前
Go 中 type、方法与指针接收者:从 str_name.Name() 看懂 Go 的类型系统
开发语言·后端·golang
Nil20818 小时前
leetcode 994腐烂的橘子
算法·leetcode·职场和发展