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
}
相关推荐
好学且牛逼的马41 分钟前
【HOT100|1 LeetCode 1. 两数之和】
数据结构·算法·leetcode
ʚ希希ɞ ྀ1 小时前
leeCode hot 100 !!!持续更新中
数据结构·算法·leetcode
剪一朵云爱着1 小时前
力扣1539. 第 k 个缺失的正整数
算法·leetcode
吃着火锅x唱着歌6 小时前
LeetCode 2016.增量元素之间的最大差值
数据结构·算法·leetcode
元亓亓亓8 小时前
LeetCode热题100--46. 全排列--中等
算法·leetcode·职场和发展
墨染点香8 小时前
LeetCode 刷题【146. LRU 缓存】
leetcode·缓存·哈希算法
qk学算法8 小时前
力扣滑动窗口题目-76最小覆盖子串&&1234替换子串得到平衡字符串
数据结构·算法·leetcode
小欣加油8 小时前
leetcode 860 柠檬水找零
c++·算法·leetcode·职场和发展·贪心算法
还是码字踏实8 小时前
基础数据结构之数组的矩阵遍历:螺旋矩阵(LeetCode 54 中等题)
数据结构·leetcode·矩阵·螺旋矩阵
周杰伦_Jay9 小时前
【主流开发语言深度对比】Python/Go/Java/JS/Rust/C++评测
开发语言·python·golang