-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.cpp
81 lines (77 loc) · 2.17 KB
/
Solution.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
class Trie {
public:
vector<Trie*> children;
bool is_end;
Trie() {
children = vector<Trie*>(26, nullptr);
is_end = false;
}
void insert(const string& word) {
Trie* cur = this;
for (char c : word) {
c -= 'a';
if (cur->children[c] == nullptr) {
cur->children[c] = new Trie;
}
cur = cur->children[c];
}
cur->is_end = true;
}
};
class Solution {
public:
vector<string> maxRectangle(vector<string>& words) {
unordered_map<int, vector<string>> d;
int maxL = 0, maxS = 0;
vector<string> ans;
vector<string> t;
Trie* trie = new Trie();
for (auto& w : words) {
maxL = max(maxL, (int) w.size());
d[w.size()].emplace_back(w);
trie->insert(w);
}
auto check = [&](vector<string>& mat) {
int m = mat.size(), n = mat[0].size();
int ans = 1;
for (int j = 0; j < n; ++j) {
Trie* node = trie;
for (int i = 0; i < m; ++i) {
int idx = mat[i][j] - 'a';
if (!node->children[idx]) {
return 0;
}
node = node->children[idx];
}
if (!node->is_end) {
ans = 2;
}
}
return ans;
};
function<void(vector<string>&)> dfs = [&](vector<string>& ws) {
if (ws[0].size() * maxL <= maxS || t.size() >= maxL) {
return;
}
for (auto& w : ws) {
t.emplace_back(w);
int st = check(t);
if (st == 0) {
t.pop_back();
continue;
}
if (st == 1 && maxS < t.size() * t[0].size()) {
maxS = t.size() * t[0].size();
ans = t;
}
dfs(ws);
t.pop_back();
}
};
for (auto& [_, ws] : d) {
t.clear();
dfs(ws);
}
return ans;
}
};