-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0318_maxProduct.cc
68 lines (63 loc) · 1.19 KB
/
Problem_0318_maxProduct.cc
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
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Solution
{
public:
int maxProduct(vector<string> &words)
{
unordered_map<int, int> map;
for (auto &word : words)
{
// 位运算优化
int mask = 0;
int n = word.length();
for (auto &c : word)
{
mask |= (1 << (c - 'a'));
}
if (map.count(mask))
{
if (n > map[mask])
{
map[mask] = n;
}
}
else
{
map[mask] = n;
}
}
int ans = 0;
for (auto &[mask1, len1] : map)
{
for (auto &[mask2, len2] : map)
{
if ((mask1 & mask2) == 0)
{
ans = std::max(ans, len1 * len2);
}
}
}
return ans;
}
};
void test()
{
Solution s;
vector<string> w1 = {"abcw", "baz", "foo", "bar", "xtfn", "abcdef"};
vector<string> w2 = {"a", "ab", "abc", "d", "cd", "bcd", "abcd"};
vector<string> w3 = {"a", "aa", "aaa", "aaaa"};
EXPECT_EQ_INT(16, s.maxProduct(w1));
EXPECT_EQ_INT(4, s.maxProduct(w2));
EXPECT_EQ_INT(0, s.maxProduct(w3));
EXPECT_SUMMARY;
}
int main()
{
test();
return 0;
}