Golang | Leetcode Golang题解之第211题添加与搜索单词-数据结构设计

题目:

题解:

Go 复制代码
type TrieNode struct {
    children [26]*TrieNode
    isEnd    bool
}

func (t *TrieNode) Insert(word string) {
    node := t
    for _, ch := range word {
        ch -= 'a'
        if node.children[ch] == nil {
            node.children[ch] = &TrieNode{}
        }
        node = node.children[ch]
    }
    node.isEnd = true
}

type WordDictionary struct {
    trieRoot *TrieNode
}

func Constructor() WordDictionary {
    return WordDictionary{&TrieNode{}}
}

func (d *WordDictionary) AddWord(word string) {
    d.trieRoot.Insert(word)
}

func (d *WordDictionary) Search(word string) bool {
    var dfs func(int, *TrieNode) bool
    dfs = func(index int, node *TrieNode) bool {
        if index == len(word) {
            return node.isEnd
        }
        ch := word[index]
        if ch != '.' {
            child := node.children[ch-'a']
            if child != nil && dfs(index+1, child) {
                return true
            }
        } else {
            for i := range node.children {
                child := node.children[i]
                if child != nil && dfs(index+1, child) {
                    return true
                }
            }
        }
        return false
    }
    return dfs(0, d.trieRoot)
}
相关推荐
pixcarp21 小时前
知识库系统的内容资产闭环怎么设计
服务器·数据库·后端·golang
张忠琳1 天前
【Go 1.26.4】Golang Select 深度解析
开发语言·后端·golang
提笔了无痕1 天前
如何用Go实现整套RAG流程
开发语言·后端·golang
一只齐刘海的猫1 天前
【Leetcode】找到字符串中所有字母异位词
算法·leetcode·职场和发展
wlsh151 天前
Go 错误处理
golang
geovindu1 天前
go: Generators Pattern
开发语言·后端·设计模式·golang·生成器模式
凌波粒1 天前
LeetCode--108.将有序数组转换为二叉搜索树(二叉树)
算法·leetcode·职场和发展
兰令水1 天前
leecodecode【面试150】【2026.6.13打卡-java版本】
java·算法·leetcode
临沂堇1 天前
刷题日志 | Leetcode Hot 100 哈希
算法·leetcode·哈希算法
Navigator_Z1 天前
LeetCode //C - 1096. Brace Expansion II
c语言·算法·leetcode