add: 220529 [cpp]

This commit is contained in:
Eat-Swap 2022-05-29 12:15:23 +08:00
parent 6f19a59f85
commit 2ea19afe35
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 40 additions and 1 deletions

39
cpp/2205/220529.cpp Normal file
View File

@ -0,0 +1,39 @@
#include <iostream>
#include <string>
#include <vector>
#include <cstdint>
/**
* 318. Maximum Product of Word Lengths
* Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0.
*/
class Solution {
public:
static int maxProduct(const std::vector<std::string>& words) {
const int n = words.size();
std::vector<std::pair<uint16_t, uint32_t>> w;
w.reserve(n);
for (const std::string& s : words) {
uint32_t set = 0;
for (const char c : s)
set |= 1 << (c - 'a');
w.emplace_back(s.length(), set);
}
int ret = 0;
for (int i = 0; i < n; ++i) {
const auto& [l1, s1] = w[i];
for (int j = i + 1; j < n; ++j) {
const auto& [l2, s2] = w[j];
if (!(s1 & s2))
ret = std::max(ret, l1 * l2);
}
}
return ret;
}
};
int main() {
std::cout << Solution::maxProduct({"abcw","baz","foo","bar","xtfn","abcdef"});
return 0;
}

View File

@ -3,4 +3,4 @@ PROJECT(2205)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2205 220528-CN.cpp)
ADD_EXECUTABLE(2205 220529.cpp)