The Ransom Note solutions are below.
15 Jun 2024•Easy•C++ / Python / TypeScript
Ransom Note
C++, Python and TypeScript solutions for Ransom Note.
Solution files
Python•ransom-note/synced-solution.py
def canConstruct(ransomNote, magazine):
from collections import Counter
ransom_count = Counter(ransomNote)
magazine_count = Counter(magazine)
for char, count in ransom_count.items():
if magazine_count[char] < count:
return False
return True
C++•ransom-note/synced-solution.cpp
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char, int> count;
for (char c : magazine) {
count[c]++;
}
for (char c : ransomNote) {
if (count[c] <= 0) {
return false;
}
count[c]--;
}
return true;
}
};
TypeScript•ransom-note/synced-solution.ts
function canConstruct(ransomNote: string, magazine: string): boolean {
const count = new Map<string, number>();
for (const char of magazine) {
count.set(char, (count.get(char) || 0) + 1);
}
for (const char of ransomNote) {
if ((count.get(char) || 0) <= 0) {
return false;
}
count.set(char, count.get(char)! - 1);
}
return true;
}