-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy path318. Maximum Product of Word Lengths.cpp
37 lines (34 loc) · 1.19 KB
/
318. Maximum Product of Word Lengths.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
// Solution 1. Straight forward, 165ms
class Solution {
public:
int maxProduct(vector<string>& words) {
int maxlen = 0;
for(int i = 0; i < words.size(); i++)
for(int j = i + 1; j < words.size(); j++){
if(words[i].size() * words[j].size() <= maxlen) continue;
if(noCommon(words[i], words[j])) maxlen = max(maxlen, (int)(words[i].size() * words[j].size()));
}
return maxlen;
}
bool noCommon(string& a, string& b){
for(auto x: a)
for(auto y: b)
if(x == y) return false;
return true;
}
};
// Solution 2. Bit Manipulation, 43ms
class Solution {
public:
int maxProduct(vector<string>& words) {
int maxlen = 0;
vector<int>val(words.size());
for(int i = 0; i < words.size(); i++)
for(auto c: words[i]) val[i] |= (1 << (c - 'a'));
for(int i = 0; i < words.size(); i++)
for(int j = i + 1; j < words.size(); j++)
if((val[i] & val[j]) == 0 && words[i].size() * words[j].size() > maxlen)
maxlen = max(maxlen, (int)(words[i].size() * words[j].size()));
return maxlen;
}
};