Skip to content

Commit 179d386

Browse files
authored
Create solution.cpp
1 parent d4192aa commit 179d386

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

RansomNote/solution.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#include <unordered_map>
2+
3+
class Solution {
4+
public:
5+
bool canConstruct(string ransomNote, string magazine)
6+
{
7+
// Count letters in ransom note
8+
unordered_map<char, int> noteMap;
9+
for (auto letter : ransomNote)
10+
noteMap[letter]++;
11+
12+
// Count letters in magazine
13+
unordered_map<char, int> magazineMap;
14+
for (auto letter : magazine)
15+
magazineMap[letter]++;
16+
17+
// Check if letters in the ransom note are avilable in the magazine
18+
for (const auto& [letter, count] : noteMap)
19+
{
20+
if (noteMap[letter] > magazineMap[letter])
21+
{
22+
// There are more letters used in the ransom note then what is available in the magazine
23+
// This note cannot be made from this magazine
24+
return false;
25+
}
26+
}
27+
28+
// If we reached here then all letters in the ransom note could be used from the magazine
29+
return true;
30+
}
31+
};

0 commit comments

Comments
 (0)