3.Ransom Note
leetcode leetcode may challenge leetcode premium leetcode premium for free leetcode problems leetcode 200 leetcode dynamic programming leetcode login leetcode array leetcode amazon leetcode anagrams leetcode app leetcode api leetcode april challenge leetcode asteroid collision leetcode atoi leetcode binary search leetcode backtracking leetcode burst balloons leetcode bfs leetcode biweekly contest leetcode bst leetcode binary tree camera leetcodebipartite grap
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Note:
You may assume that both strings contain only lowercase letters.
You may assume that both strings contain only lowercase letters.
canConstruct("a", "b") -> false canConstruct("aa", "ab") -> false canConstruct("aa", "aab") -> true
Solution in Java:
public class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
Map<Character, Integer> freq = new HashMap<>();
for(char c: magazine.toCharArray()) {
if(freq.containsKey(c)) {
freq.put(c, freq.get(c) + 1);
} else {
freq.put(c, 1);
}
}
for(char c: ransomNote.toCharArray()) {
if (freq.containsKey(c)) {
if(freq.get(c) > 1) {
freq.put(c, freq.get(c) - 1);
} else {
freq.remove(c);
}
}else{
return false;
}
}
return true;
}
}