-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconcatenatedWords.cpp
More file actions
32 lines (31 loc) · 986 Bytes
/
concatenatedWords.cpp
File metadata and controls
32 lines (31 loc) · 986 Bytes
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
30
31
32
// Source: https://leetcode.com/problems/concatenated-words/
// Author: Miao Zhang
// Date: 2021-02-14
class Solution {
public:
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
if (words.size() <= 2) return {};
unordered_set<string> wordset(words.begin(), words.end());
vector<string> res;
for (string word: words) {
wordset.erase(word);
int n = word.size();
if (n == 0) continue;
vector<bool> dp(n + 1, false);
dp[0] = true;
for (int i = 0; i <= n; i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && wordset.count(word.substr(j, i - j))) {
dp[i] = true;
break;
}
}
}
if (dp.back()) {
res.push_back(word);
}
wordset.insert(word);
}
return res;
}
};