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
}
相关推荐
福大大架构师每日一题16 小时前
go-zero v1.9.3 版本更新:一致性哈希负载均衡、gRPC优化、链路追踪修复、ORM完善等重要提升
golang·负载均衡·哈希算法
努力学算法的蒟蒻18 小时前
day27(12.7)——leetcode面试经典150
算法·leetcode·面试
CoderYanger20 小时前
动态规划算法-子序列问题(数组中不连续的一段):28.摆动序列
java·算法·leetcode·动态规划·1024程序员节
有时间要学习20 小时前
面试150——第二周
数据结构·算法·leetcode
小白程序员成长日记1 天前
2025.12.03 力扣每日一题
算法·leetcode·职场和发展
元亓亓亓1 天前
LeetCode热题100--20. 有效的括号--简单
linux·算法·leetcode
熊猫_豆豆1 天前
LeetCode 49.字母异位组合 C++解法
数据结构·算法·leetcode
小武~1 天前
Leetcode 每日一题C 语言版 -- 234 basic calculator
linux·c语言·leetcode
小白程序员成长日记1 天前
2025.12.02 力扣每日一题
数据结构·算法·leetcode
吃着火锅x唱着歌1 天前
LeetCode 3583.统计特殊三元组
算法·leetcode·职场和发展