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)
}
相关推荐
念何架构之路4 小时前
go-grpc设计思想
开发语言·后端·golang
microrain4 小时前
SagooIoT 的缓存换后端只改一行配置,文件后端连 Redis 都不需要
物联网·缓存·golang·sagooiot
y1su6 小时前
Leetcode 字符串模板
java·数据结构·算法·leetcode·职场和发展·动态规划
喵了几个咪6 小时前
GoWind ShortPlay 深度拆解:三服务 BFF + Core,一条请求的完整工程链路
golang·gowind
lvwangshu9 小时前
P8981 「DROI」Round 1 距离 题解
动态规划·图论·题解·dp·树形dp·技巧·换根dp·性质题·思维好题
Xin77012 小时前
LeetCode 46. 全排列(回溯法)
leetcode
文丑颜不良啊14 小时前
LeetCode476~500题目解析
java·leetcode
Tsuki_tl16 小时前
【优选算法:双指针】——复写零题解
java·c++·算法·leetcode·数组·双指针·复写零
Cccp.12317 小时前
【leetcode】(十四)从暴力递归到动态规划
数据结构·算法·leetcode·动态规划
旖旎夜光18 小时前
LeetCode 215: 数组中的第K个最大元素 (快速排序) —— 题解
c++·学习·算法·leetcode·力控