-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path472.cpp
More file actions
66 lines (60 loc) · 1.51 KB
/
Copy path472.cpp
File metadata and controls
66 lines (60 loc) · 1.51 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include "common.h"
using namespace std;
class Solution {
vector<Solution*> childrens;
bool leaf;
public:
Solution()
: childrens(26), leaf(false) {
}
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
remove_if(words.begin(), words.end(), [](string& s) {
return s.empty();
});
sort(words.begin(), words.end(), [](string& s1, string& s2) {
return s1.size() < s2.size();
});
vector<string> rst;
for (int i = 0; i < words.size(); ++i) {
if (helper(words[i], true)) {
rst.push_back(words[i]);
}
}
return rst;
}
bool helper(string& word, bool insert) {
auto* node = this;
for (int i = 0; i < word.size(); ++i) {
int index = word[i] - 'a';
if (node->childrens[index] == nullptr) {
if (!insert) {
return false;
}
node->childrens[index] = new Solution;
}
node = node->childrens[index];
if (node->leaf) {
if (i + 1 == word.size()) {
return true;
}
string sub_str = word.substr(i + 1);
if (helper(sub_str, false)) {
return true;
}
}
}
if (insert) { node->leaf = true; }
return false;
}
};
int main() {
Solution s;
vector<string> v = {"cat", "cats", "catsdogcats", "dog", "dogcatsdog", "hippopotamuses", "rat", "ratcatdogcat"};
auto rst = s.findAllConcatenatedWordsInADict(v);
cout << "[";
for (auto& s : rst) {
cout << "\"" << s << "\", ";
}
cout << "]" << endl;
return 0;
}