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
}
相关推荐
紧跟先前的步伐12 分钟前
Go AI Agent 实战 14|多轮对话与上下文历史管理
人工智能·ai·golang·1024程序员节
如何原谅奋力过但无声18 分钟前
【LeetCode hot100】代码随想录未cover部分
数据结构·算法·leetcode
microrain19 分钟前
设备报文怎么变,SagooIoT 只约定三个函数名
javascript·物联网·golang·sagooiot
紧跟先前的步伐1 小时前
Go AI Agent 实战 15|context.Context、超时与取消机制
人工智能·安全·ai·golang·1024程序员节
编程的一拳超人1 小时前
【元宝搜索开发者征文大赛】四语实战:Java/Python/Go/Node.js 构建 AI 搜索应用全攻略
java·python·golang·node.js·agent
文丑颜不良啊1 小时前
LeetCode701~725题目解析
java·leetcode
木井巳3 小时前
【动态规划: 线性dp】解码方法
java·算法·leetcode·动态规划·推荐算法
java_nnnn12 小时前
LeetCode刷题滑动窗口(串联所有单词的子串+最小覆盖的子串)Java
算法·leetcode·职场和发展
Navigator_Z13 小时前
LeetCode //C - 1301. Number of Paths with Max Score
c语言·算法·leetcode
Nuanyt15 小时前
LeetCode Hot100 刷题笔记 · 普通数组专题
java·笔记·算法·leetcode