【力扣】472. 连接词

这篇博客介绍了LeetCode 472题目的详细解析,探讨了如何找出给定字符串数组中所有由至少两个较短单词组成的连接词。文章通过字典树和深度优先搜索(DFS)的方法来解决这个问题。
摘要由CSDN通过智能技术生成
472. 连接词

给你一个 不含重复 单词的字符串数组 words ,请你找出并返回 words 中的所有 连接词 。
连接词 定义为:一个完全由给定数组中的至少两个较短单词组成的字符串。
示例 1:

输入:words = ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]
输出:["catsdogcats","dogcatsdog","ratcatdogcat"]
解释:"catsdogcats""cats", "dog""cats" 组成; 
     "dogcatsdog""dog", "cats""dog" 组成; 
     "ratcatdogcat""rat", "cat", "dog""cat" 组成。

示例 2:

输入:words = ["cat","dog","catdog"]
输出:["catdog"]

提示:

  • 1 < = w o r d s . l e n g t h < = 1 0 4 1 <= words.length <= 10^4 1<=words.length<=104
  • 0 <= words[i].length <= 1000
  • words[i] 仅由小写字母组成
  • 0 < = s u m ( w o r d s [ i ] . l e n g t h ) < = 1 0 5 0 <= sum(words[i].length) <= 10^5 0<=sum(words[i].length)<=105
题解

字典树+DFS

class Solution {
    Trie trie = new Trie();
    public List<String> findAllConcatenatedWordsInADict(String[] words) {
        List<String> ans = new ArrayList<>();
        Arrays.sort(words, (a, b) -> a.length() - b.length());   // 按字符串长度排序
        for(int i = 0; i < words.length; i++){
            String word = words[i];
            if(word.length() == 0) continue;
            if(dfs(word, 0)){   
                ans.add(word);
            }else{
                insert(word);  // 不是连接词就将其加入字典树
            }
        }
        return ans;
    }

    public boolean dfs(String word, int start){
        if(word.length() == start){   // 遍历完整个字符串
            return true;
        }
        Trie node = trie;
        for(int i = start; i < word.length(); i++){
            char ch = word.charAt(i);
            int idx = ch - 'a';
            node = node.children[idx];
            if(node == null) return false;  // 字典树中不存在当前单词
            if(node.isEnd){   // 当前单词的末尾
                if(dfs(word, i + 1)){   //  进入下一个单词遍历
                    return true;
                }
            }
        }
        return false;
    }

    public void insert(String word){  // 向字典树中插入单词
        Trie node = trie;
        for(int i = 0; i < word.length(); i++){
            char ch = word.charAt(i);
            int idx = ch - 'a';
            if(node.children[idx] == null){
                node.children[idx] = new Trie();
            }
            node = node.children[idx];
        }
        node.isEnd = true;
    }
}

// 定义字典树类
class Trie{
    Trie[] children;
    boolean isEnd;

    public Trie(){
        children = new Trie[26];
        isEnd = false;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值