Hash Tables: Ransom Note

  • + 10 comments

    One possible java solution:

    public class Solution {
        Map<String, Integer> magazineMap;
        Map<String, Integer> noteMap;
        
        public Solution(String magazine, String note) {
            magazineMap = new HashMap<String, Integer>();
            noteMap = new HashMap<String, Integer>();
            
            for (String word : magazine.split(" ")) {
                Integer i = magazineMap.get(word);
                
                if (i == null) {
                    magazineMap.put(word, 1);
                } else {
                    magazineMap.put(word, i + 1);
                }
            }
            
            for (String word : note.split(" ")) {
                Integer i = noteMap.get(word);
                
                if (i == null) {
                    noteMap.put(word, 1);
                } else {
                    noteMap.put(word, i + 1);
                }
            }
        }
        
        public boolean solve() {
            for (Map.Entry<String, Integer> entry : noteMap.entrySet()) {
                Integer i = magazineMap.get(entry.getKey());
                
                if (i == null) {
                    return false;
                } else {
                    if (entry.getValue() > i) {
                        return false;
                    }
                }
            }
            return true;
        }