problems: add number of matching subsequences
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
891c50440e
commit
d83859da38
1 changed files with 34 additions and 0 deletions
34
problems/number-of-matching-subsequences.cpp
Normal file
34
problems/number-of-matching-subsequences.cpp
Normal file
|
@ -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<string, int> preprocess(const vector<string>& words) const
|
||||
{
|
||||
map<string, int> histogram;
|
||||
|
||||
for (auto& w : words) {
|
||||
histogram[w]++;
|
||||
}
|
||||
|
||||
return histogram;
|
||||
}
|
||||
|
||||
public:
|
||||
int numMatchingSubseq(string s, vector<string>& 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);
|
||||
});
|
||||
}
|
||||
};
|
Loading…
Reference in a new issue