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
}
相关推荐
molaifeng3 小时前
Go 语言如何实现高性能网络 I/O:Netpoller 模型揭秘
开发语言·网络·golang
老鼠只爱大米4 小时前
LeetCode算法题详解 239:滑动窗口最大值
算法·leetcode·双端队列·滑动窗口·滑动窗口最大值·单调队列
Lips6116 小时前
2026.1.11力扣刷题笔记
笔记·算法·leetcode
pumpkin845148 小时前
Go 学习全景引子:理解设计理念与工程思路
python·学习·golang
wen__xvn8 小时前
代码随想录算法训练营DAY14第六章 二叉树 part02
数据结构·算法·leetcode
Ka1Yan8 小时前
[数组] - 代码随想录(2-6)
数据结构·算法·leetcode
漫随流水9 小时前
leetcode算法(104.二叉树的最大深度)
数据结构·算法·leetcode·二叉树
DICOM医学影像9 小时前
7. go语言从零实现以太坊请求端 - 查询区块链账户余额 - 手写JSONRPC
golang·区块链·以太坊·web3.0·jsonrpc·从零实现以太坊
pumpkin8451411 小时前
Go 基础语法全景
开发语言·后端·golang
圣保罗的大教堂12 小时前
leetcode 3453. 分割正方形 I 中等
leetcode