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)
}
相关推荐
o0o_-_10 小时前
【go/gopls/mcp】官方gopls内置mcp server使用
开发语言·后端·golang
_不会dp不改名_12 小时前
leetcode_21 合并两个有序链表
算法·leetcode·链表
吃着火锅x唱着歌12 小时前
LeetCode 3302.字典序最小的合法序列
leetcode
睡不醒的kun12 小时前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌12 小时前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
爱编程的化学家15 小时前
代码随想录算法训练营第十一天--二叉树2 || 226.翻转二叉树 / 101.对称二叉树 / 104.二叉树的最大深度 / 111.二叉树的最小深度
数据结构·c++·算法·leetcode·二叉树·代码随想录
吃着火锅x唱着歌16 小时前
LeetCode 1446.连续字符
算法·leetcode·职场和发展
愚润求学16 小时前
【贪心算法】day10
c++·算法·leetcode·贪心算法
Tisfy17 小时前
LeetCode 0966.元音拼写检查器:三个哈希表实现
leetcode·字符串·散列表·题解·哈希表
ゞ 正在缓冲99%…17 小时前
leetcode35.搜索插入位置
java·算法·leetcode·二分查找