forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-product-of-word-lengths.cpp
65 lines (62 loc) · 2.21 KB
/
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
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
// Time: O(n) ~ O(n^2)
// Space: O(n)
// Counting Sort + Pruning + Bit Manipulation
class Solution {
public:
int maxProduct(vector<string>& words) {
words = counting_sort(words);
vector<int> bits(words.size());
for (int i = 0; i < words.size(); ++i) {
for (const auto& c : words[i]) {
bits[i] |= (1 << (c - 'a'));
}
}
int max_product = 0;
for (int i = 0; i + 1 < words.size() && pow(words[i].length(), 2) > max_product; ++i) {
for (int j = i + 1; j < words.size() && words[i].length() * words[j].length() > max_product; ++j) {
if (!(bits[i] & bits[j])) {
max_product = words[i].length() * words[j].length();
}
}
}
return max_product;
}
vector<string> counting_sort(const vector<string>& words) {
const int k = 1000; // k is max length of words in the dictionary
vector<vector<string>> buckets(k);
for (const auto& word : words) {
buckets[word.length()].emplace_back(word);
}
vector<string> res;
for (int i = k - 1; i >= 0; --i) {
if (!buckets[i].empty()) {
move(buckets[i].begin(), buckets[i].end(), back_inserter(res));
}
}
return res;
}
};
// Time: O(nlogn) ~ O(n^2)
// Space: O(n)
// Sorting + Pruning + Bit Manipulation
class Solution2 {
public:
int maxProduct(vector<string>& words) {
sort(words.begin(), words.end(), [](const string& a, const string& b) { return a.length() > b.length(); });
vector<int> bits(words.size());
for (int i = 0; i < words.size(); ++i) {
for (const auto& c : words[i]) {
bits[i] |= (1 << (c - 'a'));
}
}
int max_product = 0;
for (int i = 0; i + 1 < words.size() && pow(words[i].length(), 2) > max_product; ++i) {
for (int j = i + 1; j < words.size() && words[i].length() * words[j].length() > max_product; ++j) {
if (!(bits[i] & bits[j])) {
max_product = words[i].length() * words[j].length();
}
}
}
return max_product;
}
};