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)
}
相关推荐
52Hz1185 分钟前
力扣240.搜索二维矩阵II、160.相交链表、206.反转链表
python·算法·leetcode
We་ct15 分钟前
LeetCode 380. O(1) 时间插入、删除和获取随机元素 题解
前端·算法·leetcode·typescript
老鼠只爱大米19 分钟前
LeetCode经典算法面试题 #234:回文链表(双指针法、栈辅助法等多种方法详细解析)
算法·leetcode·链表·递归·双指针·快慢指针·回文链表
狐5730 分钟前
2026-01-20-LeetCode刷题笔记-3314-构造最小位运算数组I
笔记·算法·leetcode
0和1的舞者31 分钟前
非力扣hot100-二叉树专题-刷题笔记(一)
笔记·后端·算法·leetcode·职场和发展·知识
FMRbpm34 分钟前
树的练习7--------LCR 052.递增顺序搜索树
数据结构·c++·算法·leetcode·深度优先·新手入门
源代码•宸36 分钟前
Golang原理剖析(GMP调度原理)
开发语言·经验分享·后端·面试·golang·gmp·runnext
pixcarp1 小时前
Golang web工作原理详解
开发语言·后端·学习·http·golang·web
夏鹏今天学习了吗1 小时前
【LeetCode热题100(84/100)】乘积最大子数组
算法·leetcode·职场和发展
源代码•宸2 小时前
Leetcode—3314. 构造最小位运算数组 I【简单】
开发语言·后端·算法·leetcode·面试·golang·位运算