Java HashMap solution


  • 0
    M

    I guess this is a easiest way to understand the solution

    import java.util.HashMap;
    public class Solution {
        public boolean canConstruct(String ransomNote, String magazine) {
    	
    	boolean flag = true;
    
     	HashMap<Character,Integer> m_t = new HashMap<Character,Integer>();
    
    	for(int i = 0 ; i < magazine.length(); i ++){
    		if( null != m_t.get(magazine.charAt(i)))
    			m_t.put(magazine.charAt(i),m_t.get(magazine.charAt(i)) + 1);
    		else
    			m_t.put(magazine.charAt(i),1);
    		
    	}
    
    	for(int i = 0 ; i < ransomNote.length(); i ++){
    		if( null == m_t.get(ransomNote.charAt(i)) || 0 == m_t.get(ransomNote.charAt(i))){		
    			flag = false;
    			break;
    		}else
    			m_t.put(ransomNote.charAt(i),m_t.get(ransomNote.charAt(i)) - 1 );
    				
    	}
    
    	return flag;
        }
    }
    

Log in to reply
 

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