-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path0472-concatenated-words.cpp
42 lines (38 loc) · 1.27 KB
/
0472-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
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
class Solution {
public:
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
unordered_set<string> bag(words.begin(), words.end());
vector<string> res;
for (auto word: words) {
string subWord = "";
int count = 0;
for (int i = word.size() - 1; i >= 0; i--) {
subWord = word[i] + subWord;
if (bag.count(subWord)) {
count++;
subWord = "";
}
}
if (subWord.size() == 0 && count >= 2) res.push_back(word);
}
return res;
}
};
*/
class Solution {
public:
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
unordered_set<string> dictionary(words.begin(), words.end());
vector<string> answer;
for (const string& word : words) {
const int length = word.size();
vector<bool> dp(length + 1); dp[0] = true;
for (int i = 1; i <= length; ++i)
for (int j = i == length; !dp[i] && j < i; ++j)
dp[i] = dp[j] && dictionary.count(word.substr(j, i - j));
if (dp[length]) answer.push_back(word);
}
return answer;
}
};