-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
43 lines (36 loc) · 1.04 KB
/
main.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
43
class Solution {
struct Node {
bool is_end = false;
unordered_map<char, Node*> children;
};
Node* root = new Node;
void put(const string& s) {
auto p = root;
for (char c : s) {
auto it = p->children.find(c);
if (it == p->children.end()) {
p->children[c] = new Node;
it = p->children.find(c);
}
p = it->second;
}
p->is_end = true;
}
public:
string longestWord(vector<string>& words) {
for (const auto& s : words) put(s);
string result, s;
function<void(Node*)> search = [&](Node* u) -> void {
if (s.size() == result.size() && s < result) result = s;
if (s.size() > result.size()) result = s;
for (const auto [c, v] : u->children) {
if (!v->is_end) continue;
s.push_back(c);
search(v);
s.pop_back();
}
};
search(root);
return result;
}
};