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))