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)
}
相关推荐
做怪小疯子2 小时前
Leetcode刷题——8.重叠区间
算法·leetcode·职场和发展
_饭团2 小时前
指针核心知识:5篇系统梳理3
c语言·数据结构·算法·leetcode·面试·学习方法·改行学it
呆萌很2 小时前
【GO】数组练习题
golang
阿Y加油吧3 小时前
力扣打卡——day01
java·算法·leetcode
Tisfy3 小时前
LeetCode 1727.重新排列后的最大子矩阵:枚举矩形底边是哪一行 + 排序
算法·leetcode·矩阵
_饭团4 小时前
指针核心知识:5篇系统梳理2
c语言·笔记·学习·leetcode·面试·改行学it
呆萌很5 小时前
【GO】Map练习题
golang
阿Y加油吧5 小时前
力扣打卡——盛最多水的容器、三数之和
算法·leetcode·排序算法
玛卡巴卡ldf5 小时前
【LeetCode 手撕算法】(子串) 560-和为 K 的子数组
java·数据结构·算法·leetcode
喵喵蒻葉睦7 小时前
力扣 hot100 滑动窗口最大值 单调双端队列 java 简单题解
java·数据结构·算法·leetcode·双端队列·滑动窗口·队列