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)
}
相关推荐
小刘不想改BUG10 分钟前
LeetCode LCR 010 和为 K 的子数组 (Java)
java·算法·leetcode
{⌐■_■}1 小时前
【kafka】kafka概念,使用技巧go示例
golang·kafka·linq
小雅痞1 小时前
[Java][Leetcode middle] 12. 整数转罗马数字
java·linux·leetcode
Espresso Macchiato1 小时前
Leetcode 3551. Minimum Swaps to Sort by Digit Sum
leetcode·排序·leetcode medium·leetcode 3551·leetcode周赛450
Villiam_AY2 小时前
Go 后端中双 token 的实现模板
开发语言·后端·golang
緈福的街口13 小时前
【leetcode】2900. 最长相邻不相等子序列 I
算法·leetcode·职场和发展
进击的小白菜14 小时前
LeetCode 153. 寻找旋转排序数组中的最小值:二分查找法详解及高频疑问解析
数据结构·算法·leetcode
Chandler2415 小时前
Go语言 GORM框架 使用指南
开发语言·后端·golang·orm
wktomo17 小时前
GO语言学习(二)
学习·golang
緈福的街口17 小时前
【leetcode】144. 二叉树的前序遍历
算法·leetcode