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)
}
相关推荐
alphaTao1 天前
LeetCode 每日一题 2026/5/4-2026/5/10
算法·leetcode·职场和发展
Achou.Wang1 天前
go 语言条件变量和信号量
golang
Tisfy1 天前
LeetCode 3629.通过质数传送到达终点的最少跳跃次数:埃式筛+BFS
算法·leetcode·宽度优先·质数·埃式筛
大大杰哥1 天前
leetcode hot100(2)双指针,滑动窗口
数据结构·算法·leetcode
平凡但不平庸的码农1 天前
Go 语言基础语法
开发语言·后端·golang
风筝在晴天搁浅1 天前
LeetCode CodeTop 113.路径总和Ⅱ
算法·leetcode
水木流年追梦1 天前
【python因果库实战26】逆概率加权模型1
开发语言·python·算法·leetcode
SiYuanFeng1 天前
面试大厂leetcode重点题型简洁明快复习(dfs/bfs,动态规划,链表,滑动窗口/双指针,回溯,ACM型输入输出,二分)
leetcode·面试·coding
Chase_______1 天前
【算法】LeetCode 1052 & 3679:定长滑动窗口进阶——增益最大化与频率约束贪心
算法·leetcode
凯瑟琳.奥古斯特1 天前
力扣1367:二叉树中查找链表路径
数据结构·算法·leetcode·链表