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)
}
相关推荐
6Hzlia3 小时前
【Hot 100 刷题计划】 LeetCode 48. 旋转图像 | C++ 矩阵变换题解
c++·leetcode·矩阵
Morwit5 小时前
【力扣hot100】 1. 两数之和
数据结构·c++·算法·leetcode·职场和发展
py有趣5 小时前
力扣热门100题之岛屿的数量(DFS/BFS经典题)
leetcode·深度优先·宽度优先
qinian_ztc6 小时前
frida 14.2.18 安装报错解决
算法·leetcode·职场和发展
Wenweno0o7 小时前
Eino - 错误处理与稳定性
golang·智能体·eino
田梓燊8 小时前
2026/4/11 leetcode 3741
数据结构·算法·leetcode
王码码20358 小时前
Go语言中的Elasticsearch操作:olivere实战
后端·golang·go·接口
Tomhex8 小时前
Go语言import用法详解
golang·go
小肝一下10 小时前
每日两道力扣,day8
c++·算法·leetcode·哈希算法·hot100
Tomhex10 小时前
Golang空白导入的真正用途
golang·go