Golang | Leetcode Golang题解之第472题连接词

题目:

题解:

Go 复制代码
type trie struct {
    children [26]*trie
    isEnd    bool
}

func (root *trie) insert(word string) {
    node := root
    for _, ch := range word {
        ch -= 'a'
        if node.children[ch] == nil {
            node.children[ch] = &trie{}
        }
        node = node.children[ch]
    }
    node.isEnd = true
}

func (root *trie) dfs(vis []bool, word string) bool {
    if word == "" {
        return true
    }
    if vis[len(word)-1] {
        return false
    }
    vis[len(word)-1] = true
    node := root
    for i, ch := range word {
        node = node.children[ch-'a']
        if node == nil {
            return false
        }
        if node.isEnd && root.dfs(vis, word[i+1:]) {
            return true
        }
    }
    return false
}

func findAllConcatenatedWordsInADict(words []string) (ans []string) {
    sort.Slice(words, func(i, j int) bool { return len(words[i]) < len(words[j]) })

    root := &trie{}
    for _, word := range words {
        if word == "" {
            continue
        }
        vis := make([]bool, len(word))
        if root.dfs(vis, word) {
            ans = append(ans, word)
        } else {
            root.insert(word)
        }
    }
    return
}
相关推荐
爱学习的小邓同学12 小时前
Golang --- (1)第一个Golang程序
开发语言·后端·golang
Xin77016 小时前
LeetCode 23.合并 K 个升序链表(分治递归)
leetcode
路多辛17 小时前
全能型 Agent covo-agent v0.0.7 发布:TUI 新增 LLM 内联自动补全
golang
圣殿骑士-Khtangc18 小时前
Gin优雅关停与平滑重启从零停机到热更新
golang·gin
程序员z718 小时前
深入理解 GMP 模型:Go 协程调度器的设计与调度场景全解析
服务器·网络·golang
Nil20818 小时前
leetcode 105从前序和中序遍历序列构造二叉树
算法·leetcode·职场和发展
爱学习的小邓同学19 小时前
Golang语言入门
开发语言·后端·golang
Nil20819 小时前
leetcode 114二叉树展开为链表
leetcode·链表·深度优先
cz071019 小时前
hot100_搜索二维矩阵 II
算法·leetcode
路多辛21 小时前
全能型 Go Agent 框架 covonaut v1.0.8 发布:新增行内补全与多后端可观测性
开发语言·golang·agent