JavaScript Solution Using Map


  • 0
    V
    var canConstruct = function(ransomNote, magazine) {
        var map = {};
        var mchars = magazine.split('');
        var rchars = ransomNote.split('');
        
        var i;
        for(i = 0; i < mchars.length; i++) {
            map[mchars[i]] = (map[mchars[i]] || 0) + 1;
        }
    
        for(i = 0; i < rchars.length; i++) {
            map[rchars[i]] = (map[rchars[i]] || 0) - 1;
            if(map[rchars[i]] < 0) {
                return false;
            }
        }
        return true;
    };
    

Log in to reply
 

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