HashMap solution, very simple and easy to understand


  • 0
    public class Solution {
        public boolean canConstruct(String ransomNote, String magazine) {
            Map<Character,Integer> hm = new HashMap<Character,Integer>();
            //put magazine into map
            for(int i=0;i<magazine.length();i++){
                if(!hm.containsKey(magazine.charAt(i))){
                    hm.put(magazine.charAt(i),1);
                }else{
                    hm.put(magazine.charAt(i),hm.get(magazine.charAt(i))+1);
                }
            }
            //search and update the hashmap
            for(int i =0;i<ransomNote.length();i++){
                if(hm.containsKey(ransomNote.charAt(i)) && hm.get(ransomNote.charAt(i))>0){
                    hm.put(ransomNote.charAt(i),hm.get(ransomNote.charAt(i))-1);
                    continue;
                }else return false;
            }
            return true;
        }
    }

Log in to reply
 

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