forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconcatenated-words.cpp
29 lines (28 loc) · 904 Bytes
/
concatenated-words.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Time: O(n * l^2)
// Space: O(n * l)
class Solution {
public:
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
unordered_set<string> lookup(words.begin(), words.end());
vector<string> result;
for (const auto& word : words) {
vector<bool> dp(word.length() + 1);
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() && lookup.count(word.substr(i, j - i))) {
dp[j] = true;
}
}
if (dp[word.length()]) {
result.emplace_back(word);
break;
}
}
}
return result;
}
};