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
}
相关推荐
TracyCoder12310 小时前
LeetCode Hot100(46/100)——74. 搜索二维矩阵
算法·leetcode·矩阵
im_AMBER10 小时前
Leetcode 119 二叉树展开为链表 | 路径总和
数据结构·学习·算法·leetcode·二叉树
苏荷水11 小时前
万字总结LeetCode100(持续更新...)
java·算法·leetcode·职场和发展
TracyCoder12313 小时前
LeetCode Hot100(50/100)——153. 寻找旋转排序数组中的最小值
算法·leetcode·职场和发展
化学在逃硬闯CS13 小时前
Leetcode110.平衡二叉树
数据结构·c++·算法·leetcode
爱coding的橙子13 小时前
Day87:2.12:leetcode 动态规划8道题,用时3h
算法·leetcode·动态规划
努力学算法的蒟蒻14 小时前
day84(2.12)——leetcode面试经典150
算法·leetcode·面试
程序员酥皮蛋14 小时前
hot 100 第二十三题 23.反转链表
数据结构·算法·leetcode·链表
TracyCoder12315 小时前
LeetCode Hot100(51/100)——155. 最小栈
数据结构·算法·leetcode