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
}
相关推荐
ifanatic1 小时前
[每周一更]-(第159期):Go 工程师视角:容器化技术(Docker/Kubernetes)与CI/CD流程的应用场景
docker·golang·kubernetes
张烫麻辣亮。2 小时前
golang-gin包
开发语言·golang·gin
Sally璐璐2 小时前
Go正则表达式实战指南
数据库·mysql·golang
yuluo_YX2 小时前
Go Style 代码风格规范
开发语言·后端·golang
qq_172805594 小时前
Go 自建库的使用教程与测试
开发语言·后端·golang
共享家95276 小时前
优先搜索(DFS)实战
算法·leetcode·深度优先
007php0077 小时前
某大厂MySQL面试之SQL注入触点发现与SQLMap测试
数据库·python·sql·mysql·面试·职场和发展·golang
flashlight_hi8 小时前
LeetCode 分类刷题:2563. 统计公平数对的数目
python·算法·leetcode
雨中散步撒哈拉8 小时前
13、做中学 | 初一下期 Golang数组与切片
开发语言·后端·golang
0wioiw08 小时前
Go基础(③Cobra)
开发语言·后端·golang