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
}
相关推荐
迪小莫学AI2 小时前
LeetCode 2588: 统计美丽子数组数目
算法·leetcode·职场和发展
怪力乌龟4 小时前
go语言设计模式-适配器模式
设计模式·golang·适配器模式
2301_807449205 小时前
字符串相乘——力扣
java·算法·leetcode
yadanuof5 小时前
leetcode hot100 图论
leetcode·深度优先·图论
xiao--xin6 小时前
LeetCode100之二叉搜索树中第K小的元素(230)--Java
java·算法·leetcode·二叉树·树的统一迭代法
螺旋式上升abc7 小时前
GO语言学习笔记
笔记·学习·golang
记得早睡~9 小时前
leetcode654-最大二叉树
javascript·数据结构·算法·leetcode
圣保罗的大教堂9 小时前
leetcode 2070. 每一个查询的最大美丽值 中等
leetcode
田梓燊10 小时前
leetcode 95.不同的二叉搜索树 Ⅱ
数据结构·算法·leetcode
至暗时刻darkest10 小时前
go mod文件 项目版本管理
开发语言·后端·golang