-
Notifications
You must be signed in to change notification settings - Fork 0
/
200827-1.cpp
60 lines (58 loc) · 1.23 KB
/
200827-1.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
// https://leetcode-cn.com/problems/maximum-product-of-word-lengths/
#include <iostream>
#include <vector>
#include <string>
#include <unordered_set>
using namespace std;
class Solution {
public:
int maxProduct(vector<string>& words) {
int n = words.size();
vector<int> lengths(n);
for (int i = 0; i < n; ++i) {
lengths[i] = words[i].size();
}
vector<unordered_set<char>> m(n);
for (int i = 0; i < n; ++i) {
for (auto c : words[i]) {
m[i].insert(c);
}
}
int maxProd = 0;
for (int i = 0; i + 1 < n; ++i) {
for (int j = i + 1; j < n; ++j) {
bool found = false;
for (auto c : m[i]) {
if (m[j].find(c) != m[j].end()) {
found = true;
break;
}
}
if (!found) {
int prod = lengths[i] * lengths[j];
if (maxProd < prod) {
maxProd = prod;
}
}
}
}
return maxProd;
}
};
int main()
{
Solution s;
{
vector<string> words = {"abcw","baz","foo","bar","xtfn","abcdef"};
cout << s.maxProduct(words) << endl; // answer: 16
}
{
vector<string> words = {"a","ab","abc","d","cd","bcd","abcd"};
cout << s.maxProduct(words) << endl; // answer: 4
}
{
vector<string> words = {"a","aa","aaa","aaaa"};
cout << s.maxProduct(words) << endl; // answer: 0
}
return 0;
}