Concatenated Words

本文介绍了一种算法,用于从给定的不含重复单词的列表中找出所有由至少两个更短单词组成的组合词。通过示例说明了如何使用该算法,并提供了Java实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a list of words (without duplicates), please write a program that returns all concatenated words in the given list of words.

A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.

Example:

Input: ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"]

Output: ["catsdogcats","dogcatsdog","ratcatdogcat"]

Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats"; 
"dogcatsdog" can be concatenated by "dog", "cats" and "dog";
"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".

Java代码:

public static List<String> findAllConcatenatedWordsInADict(String[] words) {
        HashSet<String> strSet=new HashSet<String>();
        for(String str:words)
        if(!strSet.contains(str))strSet.add(str);
        //System.out.println(strSet);
        List<String> res=new LinkedList<String>();
        for(String str:words){
        if(isok(str,strSet))res.add(str);
        }
        return res;
    }

public static boolean isok(String str,HashSet<String> strSet){
if(str.length()==0)return false;
boolean[] dp=new boolean[str.length()+1];
dp[0]=true;
for(int i=1;i<str.length();i++){
for(int j=0;j<i;j++){
if(!dp[j])continue;
if(strSet.contains(str.substring(j,i))){
dp[i]=true;
break;
}
}
}
for(int i=1;i<str.length();i++)
if(dp[i]&&strSet.contains(str.substring(i,str.length()))){
dp[str.length()]=true;
break;
}
return dp[str.length()];
}


时间复杂度:O(N*(L^2))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值