mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
problems(cpp): add „383. Ransom Note“
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
3bcb7469d9
commit
4aea0bb137
1 changed files with 53 additions and 0 deletions
53
problems/ransom-note.cpp
Normal file
53
problems/ransom-note.cpp
Normal file
|
@ -0,0 +1,53 @@
|
|||
#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;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
Loading…
Reference in a new issue