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
}
相关推荐
爱coding的橙子5 小时前
每日算法刷题 Day3 5.11:leetcode数组2道题,用时1h(有点慢)
算法·leetcode
Dream it possible!8 小时前
LeetCode 热题 100_只出现一次的数字(96_136_简单_C++)(哈希表;哈希集合;排序+遍历;位运算)
c++·leetcode·位运算·哈希表·哈希集合
每天一个秃顶小技巧11 小时前
02.Golang 切片(slice)源码分析(一、定义与基础操作实现)
开发语言·后端·python·golang
恋喵大鲤鱼11 小时前
Golang 空结构体特性与用法
golang·空结构体
MarkHard12313 小时前
Leetcode (力扣)做题记录 hot100(34,215,912,121)
算法·leetcode·职场和发展
Kidddddult14 小时前
力扣刷题Day 46:搜索二维矩阵 II(240)
算法·leetcode·力扣
q5673152315 小时前
Go语言多线程爬虫与代理IP反爬
开发语言·爬虫·tcp/ip·golang
Chandler2415 小时前
Go语言即时通讯系统 开发日志day1
开发语言·后端·golang
是代码侠呀19 小时前
从前端视角看网络协议的演进
leetcode·开源·github·github star·github 加星
李匠202420 小时前
C++GO语言微服务基础技术②
开发语言·c++·微服务·golang