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
}
相关推荐
参.商.3 小时前
【Day41】143. 重排链表
leetcode·golang
Zaly.6 小时前
【Python刷题】LeetCode 1727 重新排列后的最大子矩阵
算法·leetcode·矩阵
捧 花6 小时前
最小生成树算法(Go)
golang·最小生成树·kruskal·prim
添尹7 小时前
Go语言基础之数组
后端·golang
liurunlin8888 小时前
Go环境搭建(vscode调试)
开发语言·vscode·golang
memcpy09 小时前
LeetCode 1456. 定长子串中元音的最大数目【定长滑窗模板题】中等
算法·leetcode·职场和发展
玛丽莲茼蒿9 小时前
LeetCode hot100【相交链表】【简单】
算法·leetcode·职场和发展
wen__xvn9 小时前
力扣模拟题刷题
算法·leetcode
不要秃头的小孩9 小时前
力扣刷题——111.二叉树的最小深度
数据结构·python·算法·leetcode
We་ct10 小时前
LeetCode 35. 搜索插入位置:二分查找的经典应用
前端·算法·leetcode·typescript·个人开发