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)
}
相关推荐
闲谈社3 分钟前
Go单元测试
golang·单元测试
zengy51 小时前
代码随想录打卡第十三天
数据结构·c++·算法·leetcode
瑶风2 小时前
go语言并发编程2-runtime
开发语言·golang·xcode
tekin2 小时前
golang 如何判断当前是否是运行单元测试?
golang·单元测试·go·test·判断是否运行单元测试
=(^.^)=哈哈哈2 小时前
Go语言实现的端口扫描工具示例
开发语言·后端·golang
孑渡3 小时前
【LeetCode】每日一题:跳跃游戏
python·算法·leetcode·游戏·职场和发展
liulanba3 小时前
leetcode--二叉树中的最长交错路径
linux·算法·leetcode
Puppet__3 小时前
【康复学习--LeetCode每日一题】3115. 质数的最大距离
学习·算法·leetcode
每天努力进步!4 小时前
LeetCode热题100刷题6:160. 相交链表、206. 反转链表、234. 回文链表、141. 环形链表、142. 环形链表 II
c++·算法·leetcode·链表
延迟满足~4 小时前
Go 安装、命令
开发语言·后端·golang