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
}
相关推荐
茴香豆的茴39 分钟前
转码刷 LeetCode 笔记[1]:3.无重复字符的最长子串(python)
leetcode
菥菥爱嘻嘻6 小时前
力扣面试150(42/150)
算法·leetcode·职场和发展
এ᭄画画的北北7 小时前
力扣-94. 二叉树的中序遍历
算法·leetcode
7 小时前
LeetCode Hot 100 搜索旋转排序数组
数据结构·算法·leetcode
设计师小聂!9 小时前
力扣热题100-------74.搜索二维矩阵
算法·leetcode·矩阵
菥菥爱嘻嘻10 小时前
力扣面试150(44/150)
javascript·leetcode·面试
姜不吃葱12 小时前
【力扣热题100】哈希——最长连续序列
算法·leetcode·哈希算法
蒟蒻小袁15 小时前
力扣面试150题--只出现一次的数字
数据结构·算法·leetcode
恣艺16 小时前
LeetCode 68:文本左右对齐
算法·leetcode·c#
Alfred king16 小时前
Leetcode 四数之和
算法·leetcode·职场和发展·数组·排序·双指针