Neat Java hash map solution


  • 0
    M
    public class Solution {
        public boolean canConstruct(String ransomNote, String magazine) {
            if (ransomNote.length() > magazine.length()) return false;
            
            HashMap<Character, Integer> map = new HashMap<>();
            
            for(int i=0; i<ransomNote.length();i++){
                map.put(ransomNote.charAt(i), map.getOrDefault(ransomNote.charAt(i), 0)+1);
            }
            int ransomNoteLength = ransomNote.length();
            for(int j=0; j<magazine.length(); j++){
                if(map.containsKey(magazine.charAt(j)) && map.get(magazine.charAt(j)) > 0){
                    ransomNoteLength--;
                    map.put(magazine.charAt(j), map.get(magazine.charAt(j))-1);
                }
            }
            return (ransomNoteLength <= 0);
        }
    }

Log in to reply
 

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