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)
}
相关推荐
橘颂TA1 小时前
【剑斩OFFER】算法的暴力美学——二分查找
算法·leetcode·面试·职场和发展·c/c++
还是码字踏实2 小时前
基础数据结构之哈希表:两数之和(LeetCode 1 简单题)
数据结构·leetcode·散列表
Kt&Rs2 小时前
11.5 LeetCode 题目汇总与解题思路
数据结构·算法·leetcode
还是码字踏实2 小时前
基础数据结构之数组的前缀和技巧:和为K的子数组(LeetCode 560 中等题)
算法·leetcode·前缀和·哈希字典
py有趣8 小时前
LeetCode算法学习之两数之和 II - 输入有序数组
学习·算法·leetcode
夏鹏今天学习了吗8 小时前
【LeetCode热题100(62/100)】搜索二维矩阵
算法·leetcode·矩阵
吃着火锅x唱着歌10 小时前
LeetCode 1128.等价多米诺骨牌对的数量
算法·leetcode·职场和发展
十八岁讨厌编程10 小时前
【算法训练营 · 补充】LeetCode Hot100(中)
算法·leetcode
钢门狂鸭11 小时前
go开发规范指引
开发语言·驱动开发·golang
小当家.10512 小时前
[LeetCode]Hot100系列.贪心总结+思想总结
算法·leetcode·职场和发展