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)
}
相关推荐
Tony Bai15 小时前
Go 2026 路线图曝光:SIMD、泛型方法与无 C 工具链 CGO —— 性能与表达力的双重飞跃?
开发语言·后端·golang
sin_hielo15 小时前
leetcode 3512
数据结构·算法·leetcode
Elias不吃糖15 小时前
LeetCode--130被围绕的区域
数据结构·c++·算法·leetcode·深度优先
I***t71615 小时前
Go环境搭建(vscode调试)
开发语言·vscode·golang
必胜刻15 小时前
Go连接Mysql数据库
数据库·mysql·golang
小马过河R15 小时前
tRPC-GO 框架Helloworld实践初体验
开发语言·分布式·后端·架构·golang·gin·beego
im_AMBER16 小时前
Leetcode 63 定长子串中元音的最大数目
c++·笔记·学习·算法·leetcode
小白程序员成长日记17 小时前
2025.11.29 力扣每日一题
数据结构·算法·leetcode
b***666118 小时前
【golang学习之旅】使用VScode安装配置Go开发环境
vscode·学习·golang
8***293119 小时前
Go基础之环境搭建
开发语言·后端·golang