From 848381110f914c03e9c7c7d99d42fa41004aac3e Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Tue, 23 Jan 2024 21:43:12 +0100 Subject: [PATCH] =?UTF-8?q?cpp:=20add=20=E2=80=9C1239.=20Maximum=20Length?= =?UTF-8?q?=20of=20a=20Concatenated=20String=20with=20Unique=20Characters?= =?UTF-8?q?=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...atenated-string-with-unique-characters.cpp | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 cpp/maximum-length-of-a-concatenated-string-with-unique-characters.cpp diff --git a/cpp/maximum-length-of-a-concatenated-string-with-unique-characters.cpp b/cpp/maximum-length-of-a-concatenated-string-with-unique-characters.cpp new file mode 100644 index 0000000..19f3230 --- /dev/null +++ b/cpp/maximum-length-of-a-concatenated-string-with-unique-characters.cpp @@ -0,0 +1,66 @@ +#include +#include +#include +#include +#include +#include + +class Solution { + static auto construct_sets(const std::vector &arr) + -> std::vector { + std::vector 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 &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 &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; +}