383. Ransom Note
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:
Example 2:
Example 3:
Constraints:
1 <= ransomNote.length, magazine.length <= 105ransomNoteandmagazineconsist of lowercase English letters.
Solution:
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < magazine.length(); i++){
char cur = magazine.charAt(i);
map.put(cur, map.getOrDefault(cur, 0) + 1);
}
for (int i = 0; i < ransomNote.length(); i++){
char cur = ransomNote.charAt(i);
if (!map.containsKey(cur)){
return false;
}else{
int count = map.get(cur);
if (count < 1){
return false;
}else{
map.put(cur, count - 1);
}
}
}
return true;
}
}
// TC: O(n)
// SC: O(n)