simple Java solution using hashmap


  • 0
    public class Solution {
        public boolean canConstruct(String ransomNote, String magazine) {
    	final int l1 = ransomNote.length();
            final int l2 = magazine.length();
            
            if(ransomNote == null || l1 == 0) return true;
            if(( l1 > l2) || ((l1 == l2) && (ransomNote != magazine))){
                return false;
            }
            
            Map<Character, Integer> mapN = new HashMap<>();
            List<Character> array = new ArrayList<>();
            for(int i=0; i<l1; i++){
            	char c = ransomNote.charAt(i);
            	if(!mapN.containsKey(c)){
            		mapN.put(c, 1);
            		array.add(c);
            	}else{
            		mapN.put(c, mapN.get(c)+1);
            	}
            }
            
            Map<Character, Integer> mapM = new HashMap<>();
            for(int i=0; i<l2; i++){
            	char c = magazine.charAt(i);
            	if(!mapM.containsKey(c)){
                            mapM.put(c, 1);
            	}else{
            		mapM.put(c, mapM.get(c)+1);
            	}
            }
            for(char c: array){
            	if(!mapM.containsKey(c) || mapN.get(c)>mapM.get(c)) return false;
            }
            return true;
        }
    }

Log in to reply
 

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