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)
}
相关推荐
旖-旎5 小时前
《LeetCode 53 最大子数组和 || LeetCode 918 环形子数组的最大和》
c++·算法·leetcode·动态规划
海石8 小时前
单调栈复健,顺便,牺牲一下吧,空间复杂度!一切献给AC
算法·leetcode
海石8 小时前
JS击败94%,Hard题想不到动态规划,那就用数组和栈试试
算法·leetcode
alphaTao10 小时前
LeetCode 每日一题 2026/7/6-2026/7/12
算法·leetcode
想吃火锅100510 小时前
【leetcode】56.合并区间js
算法·leetcode·职场和发展
wabs66610 小时前
关于动态规划【力扣72.编辑距离的思考】
算法·leetcode·动态规划
凌波粒11 小时前
LeetCode--47.全排列 II(回溯算法)
算法·leetcode·职场和发展
大侠锅锅12 小时前
第 9 篇:状态机实践——状态环 + 步进表替代 if-else 地狱
golang·边缘计算·状态机
灯澜忆梦13 小时前
iota枚举
golang
凌波粒13 小时前
LeetCode--53. 最大子序和(贪心算法)
算法·leetcode·贪心算法