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
}
相关推荐
We་ct7 分钟前
LeetCode 201. 数字范围按位与:位运算高效解题指南
开发语言·前端·javascript·算法·leetcode·typescript
木子欢儿14 分钟前
在 Fedora 上配置 Go 语言(Golang)开发环境
开发语言·后端·golang
Khsc434ka1 小时前
LeetCode-001:Python 实现哈希表求两数之和:初识哈希表
python·leetcode·散列表
yangyanping201081 小时前
Go语言学习之配置管理库Viper
开发语言·学习·golang
pixcarp1 小时前
GORM基础入门使用教程
数据库·golang
呆萌很1 小时前
【GO】结构体定义练习题
golang
Byte不洛1 小时前
LeetCode双指针经典题
c++·算法·leetcode·双指针
米粒11 小时前
力扣算法刷题 Day 34
算法·leetcode·职场和发展
田梓燊2 小时前
leetcode 189
算法·leetcode·职场和发展
一条闲鱼_mytube2 小时前
【深入理解】HTTP/3 与 QUIC 协议:从原理到 Go 语言实战
网络协议·http·golang