Java simple solution counting letters frequency


  • 0
    M

    Very simple solution, counting the frequency of letters in both magazine and ransom note, then check if the number of letters in magazine is not less than in ransom note.

    public class Solution {
        
        public boolean canConstruct(String ransomNote, String magazine) {
            
            Map<Character, Integer> magFrequency = new HashMap<>();
            Map<Character, Integer> ransFrequency = new HashMap<>();
            
            for (int i = 0; i < magazine.length(); i++) {
                char c = magazine.charAt(i);
                Integer value = magFrequency.get(c);
                if (value == null) value = new Integer(1);
                else value++;
                magFrequency.put(c, value);
            }
            
            for (int j = 0; j < ransomNote.length(); j++) {
                char c = ransomNote.charAt(j);
                Integer value = ransFrequency.get(c);
                if (value == null) value = new Integer(1);
                else value++;
                ransFrequency.put(c, value);
            }
              
            for (Map.Entry<Character, Integer> entry : ransFrequency.entrySet()) {
                Integer value = magFrequency.get(entry.getKey());
                if (value == null || value < entry.getValue()) return false;
            }    
            
            return true;
        }
        
    }
    

Log in to reply
 

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