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
.
Example 1:
Input: ransomNote = "a", magazine = "b"
Output: false
Example 2:
Input: ransomNote = "aa", magazine = "ab"
Output: false
Example 3:
Input: ransomNote = "aa", magazine = "aab"
Output: true
Constraint:
1 <= ransomNote.length, magazine.length <= 10^5
ransomNote
andmagazine
consist of lowercase English letters.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Solution (Java)
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int[] a = new int[26];
int n = ransomNote.length();
for (int i = 0; i < n; i++) {
a[ransomNote.charAt(i) - 97]++;
}
for (int i = 0; i < magazine.length() && n != 0; i++) {
if (a[magazine.charAt(i) - 97] > 0) {
n--;
a[magazine.charAt(i) - 97]--;
}
}
return n == 0;
}
}
Solution 1
/**
* @param {string} ransomNote
* @param {string} magazine
* @return {boolean}
*/
var canConstruct = function(ransomNote, magazine) {
const map = new Map();
for (let i = 0; i < magazine.length; i++) {
if (map.has(magazine[i])) {
map.set(magazine[i], map.get(magazine[i]) + 1)
} else {
map.set(magazine[i], 1)
}
}
for (let i = 0; i < ransomNote.length; i++) {
if (!map.has(ransomNote[i]) || map.get(ransomNote[i]) === 0) {
return false;
}
map.set(ransomNote[i], map.get(ransomNote[i]) - 1)
}
return true;
};