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
}
相关推荐
dying_man5 分钟前
LeetCode--42.接雨水
算法·leetcode
黑听人1 小时前
【力扣 困难 C】115. 不同的子序列
c语言·leetcode
witton2 小时前
Go语言网络游戏服务器模块化编程
服务器·开发语言·游戏·golang·origin·模块化·耦合
叹一曲当时只道是寻常2 小时前
Softhub软件下载站实战开发(十六):仪表盘前端设计与实现
前端·golang
Jerry Lau3 小时前
go go go 出发咯 - go web开发入门系列(一) helloworld
开发语言·前端·golang
天下一般3 小时前
go入门 - day1 - 环境搭建
开发语言·后端·golang
前端拿破轮3 小时前
🤡🤡🤡面试官:就你这还每天刷leetcode?连四数相加和四数之和都分不清!
算法·leetcode·面试
无聊的小坏坏5 小时前
单调栈通关指南:从力扣 84 到力扣 42
c++·算法·leetcode
大P哥阿豪6 小时前
Go defer(二):从汇编的角度理解延迟调用的实现
开发语言·汇编·后端·golang
qq_5139704420 小时前
力扣 hot100 Day37
算法·leetcode