August 7, 2016 · LeetCode Algorithm JS

LeetCode - 383 - Ransom Note

Problem

Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.

Each letter in the magazine string can only be used once in your ransom note.

Note:You may assume that both strings contain only lowercase letters.

canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true

Try it out : https://leetcode.com/problems/ransom-note/

Javascript 200ms

/**
 * @param {string} ransomNote
 * @param {string} magazine
 * @return {boolean}
 */
var canConstruct = function(ransomNote, magazine){
    if ( ransomNote == "") {return true;}
    
    var magazineHashMap = {};
    for (var i=0;i<magazine.length;i++)
    {
        if ( magazineHashMap[magazine.charAt(i)] == null)
        {
            magazineHashMap[magazine.charAt(i)] = 1;
        }else {
            magazineHashMap[magazine.charAt(i)] += 1;    
        }
    }
    
    var ransomNoteHashMap = {};
    for (var i=0;i<ransomNote.length;i++)
    {
        if ( ransomNoteHashMap[ransomNote.charAt(i)] == null)
        {
           ransomNoteHashMap[ransomNote.charAt(i)] = 1;
        }else {
            ransomNoteHashMap[ransomNote.charAt(i)] += 1;    
        }
    }
    var keys = Object.keys(ransomNoteHashMap);
    for (var i=0; i<keys.length;i++)
    {
        if (magazineHashMap[keys[i]] == null || magazineHashMap[keys[i]] < ransomNoteHashMap[keys[i]]){
            return false;
        }
    }
    
    return true;
};