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
}
相关推荐
阿里加多6 小时前
第 4 章:Go 线程模型——GMP 深度解析
java·开发语言·后端·golang
GDAL7 小时前
Go Channel 深入全面讲解教程
golang
止语Lab9 小时前
Go GC 十年:一部延迟战争史
golang
阿里加多9 小时前
第 1 章:Go 并发编程概述
java·开发语言·数据库·spring·golang
XiYang-DING12 小时前
【LeetCode】Hash | 136.只出现一次的数字
算法·leetcode·哈希算法
嘻嘻哈哈樱桃14 小时前
俄罗斯套娃信封问题力扣--354
算法·leetcode·职场和发展
田梓燊14 小时前
2026/4/12 leetcode 1320
算法·leetcode·职场和发展
j_xxx404_14 小时前
力扣题型--链表(两数相加|两两交换链表中的节点|重排链表)
数据结构·c++·算法·leetcode·蓝桥杯·排序算法
zs宝来了14 小时前
etcd Raft 实现:分布式一致性核心原理
golang·go·后端技术
呆萌很14 小时前
【GO】为任意类型添加方法练习题
golang