1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-19 17:56:55 +02:00

cpp: add “1239. Maximum Length of a Concatenated String with Unique Characters”

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-01-23 21:43:12 +01:00
parent 0308502e2d
commit 848381110f
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,66 @@
#include <bit>
#include <cassert>
#include <cstdint>
#include <iostream>
#include <string>
#include <vector>
class Solution {
static auto construct_sets(const std::vector<std::string> &arr)
-> std::vector<uint32_t> {
std::vector<std::uint32_t> sets;
for (const auto &word : arr) {
std::uint32_t w = 0;
for (char c : word) {
auto mask = 1 << (c - 'a');
if ((w & mask) != 0) {
w = 0;
break;
}
w |= mask;
}
sets.push_back(w);
}
return sets;
}
static auto find_solution(const std::vector<std::uint32_t> &words,
std::size_t i, std::uint32_t w) -> int {
if (i == words.size()) {
return std::popcount(w);
}
auto found_solution = find_solution(words, i + 1, w);
if ((words[i] & w) == 0) {
found_solution = std::max(
found_solution, find_solution(words, i + 1, w | words[i]));
}
return found_solution;
}
public:
int maxLength(const std::vector<std::string> &arr) {
auto sets = construct_sets(arr);
return find_solution(sets, 0u, 0u);
}
};
int main() {
Solution s;
assert(s.maxLength(std::vector{std::string{"un"}, std::string{"iq"},
std::string{"ue"}}) == 4);
assert(s.maxLength(std::vector{std::string{"cha"}, std::string{"r"},
std::string{"act"}, std::string{"ers"}}) ==
6);
assert(s.maxLength(
std::vector{std::string{"abcdefghijklmnopqrstuvwxyz"}}) == 26);
return 0;
}