Leetcode

来源:互联网 发布:python snmpgetbulk 编辑:程序博客网 时间:2024/05/20 14:18
public class Solution {    public boolean canConstruct(String ransomNote, String magazine) {        if (ransomNote.length() > magazine.length()) return false;        HashMap<Character, Integer> hm = new HashMap<>();                // save all letter and its frequency into the hashmap        for (int i=0; i<ransomNote.length(); i++) {            int feq = hm.getOrDefault(ransomNote.charAt(i), 0);            hm.put(ransomNote.charAt(i), feq+1);        }                // decrease the value by 1 int the hashmap if letter in the magazine already exists in the hm        for (int j=0; j<magazine.length(); j++) {            int tmp = hm.getOrDefault(magazine.charAt(j), 0);            if (tmp != 0)                hm.put(magazine.charAt(j), tmp-1);        }                // check values in the hashmap, if all values are 0 return true        for (Integer feq : hm.values())            if (feq != 0) return false;                    return true;    }}

0 0