题目
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.
我的想法
应该可以用dp做,但不知道怎样构建dp数组
解答
jiuzhang solution:
对每一个单词建立一个一维数组,存储该单词的substring(0, j) 是否在数组words中找到。如果dp[word.length] == true 则说明这个单词拼接单词
class Solution {
public List<String> findAllConcatenatedWordsInADict(String[] words) {
HashSet<String> dic = new HashSet<>();
List<String> res = new ArrayList<>();
for(String word : words) {
dic.add(word);
}
for(String word : words) {
if(word.length() == 0) {
continue;
}
boolean[] dp = new boolean[word.length()+1];
Arrays.fill(dp,false);
dp[0] = true;
for(int i = 0; i < word.length(); i++) {
if(!dp[i]) {
continue;
}
for(int j = i + 1; j <= word.length(); j++) {
//避免把自己加进去
if(j-i != word.length() && dic.contains(word.substring(i, j))) {
dp[j] = true;
}
}
if(dp[word.length()]) {
res.add(word);
break;
}
}
}
return res;
}
}