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
}
相关推荐
西阳未落1 小时前
LeetCode——二分(进阶)
算法·leetcode·职场和发展
小羊在睡觉2 小时前
golang定时器
开发语言·后端·golang
不爱洗脚的小滕4 小时前
【Redis】三种缓存问题(穿透、击穿、双删)的 Golang 实践
redis·缓存·golang
吃着火锅x唱着歌4 小时前
LeetCode 410.分割数组的最大值
数据结构·算法·leetcode
YSRM4 小时前
Leetcode+Java+图论+最小生成树&拓扑排序
java·leetcode·图论
YSRM4 小时前
Leetcode+Java+图论+并查集
算法·leetcode·图论
小白杨树树5 小时前
【C++】力扣hot100错误总结
c++·leetcode·c#
吃着火锅x唱着歌7 小时前
LeetCode 668.乘法表中第k小的数
算法·leetcode·职场和发展
十八岁讨厌编程8 小时前
【算法训练营 · 补充】LeetCode Hot100(上)
算法·leetcode