From d83859da38d78fbc54220776c0850100c4974f54 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 20 Jul 2022 17:09:12 +0200 Subject: [PATCH] problems: add number of matching subsequences Signed-off-by: Matej Focko --- problems/number-of-matching-subsequences.cpp | 34 ++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 problems/number-of-matching-subsequences.cpp diff --git a/problems/number-of-matching-subsequences.cpp b/problems/number-of-matching-subsequences.cpp new file mode 100644 index 0000000..50e70eb --- /dev/null +++ b/problems/number-of-matching-subsequences.cpp @@ -0,0 +1,34 @@ +class Solution { + bool matches(const string& s, const string& word) const + { + auto s_i = 0; + + for (auto i = 0; s_i < s.size() && i < word.size(); i++) { + if (s[s_i] == word[i]) { + s_i++; + } + } + + return s_i == s.size(); + } + + map preprocess(const vector& words) const + { + map histogram; + + for (auto& w : words) { + histogram[w]++; + } + + return histogram; + } + +public: + int numMatchingSubseq(string s, vector& words) + { + auto histogram = preprocess(words); + return accumulate(histogram.begin(), histogram.end(), 0, [&](int acc, const auto& pair) { + return acc + (matches(pair.first, s) ? pair.second : 0); + }); + } +};