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
}
相关推荐
洛水水5 小时前
【力扣100题】30.二叉树的直径
算法·leetcode·职场和发展
洛水水8 小时前
【力扣100题】32.将有序数组转换为二叉搜索树
数据结构·算法·leetcode
如竟没有火炬9 小时前
用队列实现栈
开发语言·数据结构·python·算法·leetcode·深度优先
水木流年追梦10 小时前
大模型入门-应用篇3-Agent智能体
开发语言·python·算法·leetcode·正则表达式
洛水水10 小时前
【力扣100题】31.二叉树的层序遍历
算法·leetcode·职场和发展
洛水水10 小时前
【力扣100题】41.爬楼梯
算法·leetcode·职场和发展
Pkmer10 小时前
LeetCode 上极少见的工程级滑窗实现
python·leetcode
sheeta199811 小时前
LeetCode 每日一题笔记 日期:2026.05.13 题目:1674. 使数组互补的最少操作次数
笔记·算法·leetcode
YL2004042612 小时前
038翻转二叉树
数据结构·leetcode
Liangwei Lin13 小时前
LeetCode 287. 寻找重复数
算法·leetcode·职场和发展