题目地址:
https://leetcode.com/problems/concatenated-words/
给定一个非空英文小写字符串组成的数组 A A A,题目保证字符串两两不同,返回其所有能被至少两个别的字符串拼接而成的字符串。同一个字符串可以被多次使用。
思路是动态规划 + 字符串哈希。先将 A A A里每个字符串做哈希,然后将哈希值存入一个哈希表。我们枚举 s = A [ i ] s=A[i] s=A[i],然后设 f [ k ] f[k] f[k]是 s [ 0 : k − 1 ] s[0:k-1] s[0:k−1]最多能被 A [ 0 : i − 1 ] A[0:i-1] A[0:i−1]的多少个字符串拼接而成,那么 f [ 0 ] = 0 f[0]=0 f[0]=0对应着空串,那么在 s [ j : k ] s[j:k] s[j:k]的哈希值在哈希表的情况下, f [ j ] + 1 f[j]+1 f[j]+1可以用来更新 f [ k + 1 ] f[k+1] f[k+1],也就是说 f [ l s ] = max s [ j : l s − 1 ] ∈ S { f [ j ] + 1 } f[l_s]=\max_{s[j:l_s-1]\in S}\{f[j]+1\} f[ls]=s[j:ls−1]∈Smax{f[j]+1} S S S为哈希表。这里为了加速,我们可以在已知 f [ j ] f[j] f[j]的情况下去更新 f [ . > j ] f[.>j] f[.>j],一旦发现 f [ l s ] > 1 f[l_s]>1 f[ls]>1了就说明 s s s是可以写为若干字符串拼接的,则直接返回true。代码如下:
import java.util.*;
public class Solution {
long P = 131;
public List<String> findAllConcatenatedWordsInADict(String[] words) {
List<String> res = new ArrayList<>();
Set<Long> set = new HashSet<>();
for (String s : words) {
long ha = 0;
for (int i = 0; i < s.length(); i++) {
ha = ha * P + s.charAt(i);
}
set.add(ha);
}
for (String word : words) {
if (check(word, set)) {
res.add(word);
}
}
return res;
}
private boolean check(String s, Set<Long> set) {
int n = s.length();
int[] f = new int[n + 1];
Arrays.fill(f, -1);
f[0] = 0;
for (int i = 0; i <= n; i++) {
if (f[i] == -1) {
continue;
}
long ha = 0;
for (int j = i + 1; j <= n; j++) {
ha = ha * P + s.charAt(j - 1);
if (set.contains(ha)) {
f[j] = Math.max(f[j], f[i] + 1);
}
if (f[n] > 1) {
return true;
}
}
}
return false;
}
}
时间复杂度 O ( n l 2 ) O(nl^2) O(nl2), l l l是最长字符串长度,空间 O ( n l ) O(nl) O(nl)。
C++:
class Solution {
public:
using UL = unsigned long;
UL P = 131;
vector<string> findAllConcatenatedWordsInADict(vector<string> &words) {
vector<string> res;
unordered_set<UL> st;
for (auto &s : words) {
UL ha = 0;
for (char ch : s) ha = ha * P + ch;
st.insert(ha);
}
for (auto &s : words)
if (check(s, st)) res.push_back(s);
return res;
}
bool check(string &s, unordered_set<UL> &st) {
int n = s.size();
vector<int> f(n + 1, -1);
f[0] = 0;
for (int i = 0; i <= n; i++) {
if (f[i] == -1) continue;
UL ha = 0;
for (int j = i + 1; j <= n; j++) {
ha = ha * P + s[j - 1];
if (st.count(ha)) f[j] = max(f[i] + 1, f[j]);
if (f[n] > 1) return true;
}
}
return false;
}
};
时空复杂度一样。