思路:分别用两个map记录ransomNote和magazine中的字符以及出现的次数。最后遍历记录ransomNote的map,如果ransomNote的map中出现的magazine的map中没有出现或者出现的次数小于ransomNote的map则返回false,否则返回true;
class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
Map<Character,Integer> ransomNote_map = new HashMap<>();
Map<Character,Integer> magazine_map = new HashMap<>();
for(int i = 0 ; i < ransomNote.length() ; i++)
{
ransomNote_map.put(ransomNote.charAt(i), ransomNote_map.getOrDefault(ransomNote.charAt(i), 0) + 1);
}
for(int i = 0 ; i < magazine.length() ; i++)
{
magazine_map.put(magazine.charAt(i),magazine_map.getOrDefault(magazine.charAt(i),0) + 1);
}
for(Character c : ransomNote_map.keySet())
{
if(!magazine_map.containsKey(c) || ransomNote_map.get(c) > magazine_map.get(c))
{
return false;
}
}
return true;
}
}