Java solution with hashmap

  • 0
    public class Solution {
        public boolean canConstruct(String ransomNote, String magazine) {
            if(ransomNote == null || magazine == null) return false;
            HashMap<String, Integer> mag_hash = new HashMap();
            for(int i=0;i<magazine.length();i++){
                String c = String.valueOf(magazine.charAt(i));
                    mag_hash.put(c,mag_hash.get(c) +1);
                    mag_hash.put(c, 1);
            for(int j=0; j<ransomNote.length();j++){
                String c = String.valueOf(ransomNote.charAt(j));
                if(!mag_hash.containsKey(c)) return false;
                int val = mag_hash.get(c);
                if(val <= 0) return false;
                mag_hash.put(c, val-1);
            return true;

  • 0

    You could use HashMap of Character and Integer to prevent building a String inside for Loop.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.