题目地址:
https://www.lintcode.com/problem/concatenated-words/description
给定一个非空英文小写字符串组成的数组 A A A,题目保证字符串两两不同,返回其所有能被至少两个别的字符串拼接而成的字符串。同一个字符串可以被多次使用。
参考https://blog.csdn.net/qq_46105170/article/details/112428099。代码如下:
import java.util.*;
public class Solution {
/**
* @param words: List[str]
* @return: return List[str]
*/
public List<String> findAllConcatenatedWordsInADict(String[] words) {
// write your code here
List<String> res = new ArrayList<>();
Set<String> set = new HashSet<>();
Arrays.sort(words, (w1, w2) -> Integer.compare(w1.length(), w2.length()));
for (int i = 0; i < words.length; i++) {
if (check(words[i], set)) {
res.add(words[i]);
}
set.add(words[i]);
}
return res;
}
private boolean check(String s, Set<String> set) {
int[] dp = new int[s.length() + 1];
Arrays.fill(dp, -1);
dp[0] = 0;
for (int i = 0; i < s.length(); i++) {
if (dp[i] == -1) {
continue;
}
for (int j = s.length() - i; j >= 0; j--) {
if (set.contains(s.substring(i, i + j))) {
dp[i + j] = Math.max(dp[i + j], dp[i] + 1);
}
if (dp[s.length()] > 1) {
return true;
}
}
}
return false;
}
}
时间复杂度 O ( n l log n + n l 3 ) O(nl\log n+nl^3) O(nllogn+nl3), l l l是最长字符串长度,空间 O ( n l ) O(nl) O(nl)。