diff --git a/problems/ransom-note.cpp b/problems/ransom-note.cpp new file mode 100644 index 0000000..cdc7b79 --- /dev/null +++ b/problems/ransom-note.cpp @@ -0,0 +1,53 @@ +#include +#include +#include + +namespace { + +std::map build_freqs(const std::string& input) +{ + std::map freqs; + + for (auto c : input) { + freqs[c]++; + } + + return freqs; +} + +bool subtract(std::map available, const std::string& message) +{ + for (auto c : message) { + available[c]--; + + if (available[c] < 0) { + return false; + } + } + + return true; +} + +} + +class Solution { +public: + bool canConstruct(const std::string& ransomNote, const std::string& magazine) + { + auto available = build_freqs(magazine); + return subtract(available, ransomNote); + } +}; + +int main() +{ + Solution s; + + assert(!s.canConstruct("a", "b")); + assert(!s.canConstruct("aa", "ab")); + assert(s.canConstruct("aa", "aab")); + assert(s.canConstruct("ab", "aab")); + assert(s.canConstruct("ba", "aab")); + + return 0; +}