From 4e873f87b0c40e203b1f895dee5f8736ccf7961a Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 1 May 2024 00:53:46 +0200 Subject: [PATCH] =?UTF-8?q?cpp:=20add=20=C2=AB1915.=20Number=20of=20Wonder?= =?UTF-8?q?ful=20Substrings=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cpp/number-of-wonderful-substrings.cpp | 29 ++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 cpp/number-of-wonderful-substrings.cpp diff --git a/cpp/number-of-wonderful-substrings.cpp b/cpp/number-of-wonderful-substrings.cpp new file mode 100644 index 0000000..2c2568f --- /dev/null +++ b/cpp/number-of-wonderful-substrings.cpp @@ -0,0 +1,29 @@ +#include +#include +#include + +class Solution { + static const std::uint32_t BIT = 1; + + public: + long long wonderfulSubstrings(const std::string &word) { + long long result = 0; + + std::unordered_map freqs; + freqs[0] = 1; + + std::uint32_t mask = 0; + for (char c : word) { + mask ^= BIT << (c - 'a'); + + result += freqs[mask]; + ++freqs[mask]; + + for (auto odd_c = 0; odd_c < 10; ++odd_c) { + result += freqs[mask ^ (BIT << odd_c)]; + } + } + + return result; + } +};