Ransom Note
Problem
Given two strings ransomNote
and magazine
, return true
if ransomNote
can be constructed by using the letters from magazine
and false
otherwise.
Each letter in magazine
can only be used once in ransomNote
.
Constraints
1 <= ransomNote.length, magazine.length <= 105
ransomNote
andmagazine
consist of lowercase English letters.
Solution
The problem Ransom Note
can be solved using a hash map to count the number of each letters in both strings.
Implementation
class Solution
{
public:
bool canConstruct(string ransomNote, string magazine)
{
int letters[26];
for (int i = 0; i < 26; i++)
letters[i] = 0;
for (char ch : magazine)
letters[ch - 'a'] += 1;
for (char ch : ransomNote)
if (letters[ch - 'a']-- == 0)
return false;
return true;
}
};