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
}
相关推荐
苏琢玉35 分钟前
想让默认头像不再千篇一律,就顺手复刻了一下 GitHub 的思路
golang
熬了夜的程序员1 小时前
【LeetCode】88. 合并两个有序数组
数据结构·算法·leetcode·职场和发展·深度优先
ゞ 正在缓冲99%…10 小时前
leetcode2826.将三个组排序
算法·leetcode·动态规划
九江Mgx10 小时前
Go语言实现的简易远程传屏工具:让你的屏幕「飞」起来
golang·截图·传屏
九江Mgx13 小时前
自由通讯的魔法:Go从零实现UDP/P2P 聊天工具
golang·udp·p2p
ErizJ13 小时前
IM|im-service
golang·kafka·go·im·心跳检测
微笑尅乐15 小时前
洗牌算法讲解——力扣384.打乱数组
算法·leetcode·职场和发展
天选之女wow15 小时前
【代码随想录算法训练营——Day48】单调栈——42.接雨水、84.柱状图中最大的矩形
算法·leetcode
仰泳的熊猫16 小时前
LeetCode:773. 滑动谜题
数据结构·c++·算法·leetcode
夏鹏今天学习了吗16 小时前
【LeetCode热题100(50/100)】岛屿数量
算法·leetcode·职场和发展