O(m+n) solution using HashMap Java


  • 0
    P

    O(m+n) solution Java

    public boolean canConstruct(String ransomNote, String magazine)
    {
    HashMap<Character,Integer> hmap = new HashMap<Character,Integer>();

       if(ransomNote == null || magazine == null){
           return false;
       }
       
       for(int i=0;i<ransomNote.length();i++){
       
            if(!hmap.containsKey(ransomNote.charAt(i))){   
                hmap.put(ransomNote.charAt(i),0);    
            }else{
                int count = hmap.get(ransomNote.charAt(i));
                hmap.put(ransomNote.charAt(i),count+1);
            }
           
       }
       
       for(int i=0;i<magazine.length();i++){
       
            if(hmap.containsKey(magazine.charAt(i))){   
                int count = hmap.get(magazine.charAt(i));
                hmap.put(magazine.charAt(i),count-1);
            }
           
       }
       
       
        for(int i=0;i<ransomNote.length();i++){
            if(hmap.get(ransomNote.charAt(i))>=0)
            return false;
        }
       
       
       return true;
        
    }

Log in to reply
 

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