-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path472.cpp
More file actions
32 lines (26 loc) · 830 Bytes
/
Copy path472.cpp
File metadata and controls
32 lines (26 loc) · 830 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
class Solution {
bool dfs(unordered_set<string>& wd, string str) {
if (str.size() == 0 || wd.count(str)) return true;
for (int i = 1; i < str.size(); i++) {
if (wd.count(str.substr(0, i)) && dfs(wd, str.substr(i)))
return true;
}
return false;
}
public:
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
if (words.empty()) return {};
unordered_set<string> wd;
vector<string> ans;
sort(words.begin(), words.end(), [](const string &a, const string& b) {
return a.size() < b.size();
});
for (string& w : words) {
if (w.size() > 0 && dfs(wd, w)) {
ans.push_back(w);
}
wd.insert(w);
}
return ans;
}
};