1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 01:49:41 +01:00
LeetCode/cpp/ransom-note.cpp
Matej Focko b229608723
cpp(chore): add clang-format style and format
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-01-03 12:06:54 +01:00

50 lines
962 B
C++

#include <cassert>
#include <map>
#include <string>
namespace {
std::map<char, int> build_freqs(const std::string &input) {
std::map<char, int> freqs;
for (auto c : input) {
freqs[c]++;
}
return freqs;
}
bool subtract(std::map<char, int> available, const std::string &message) {
for (auto c : message) {
available[c]--;
if (available[c] < 0) {
return false;
}
}
return true;
}
} // namespace
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;
}