Ransom Note

来源:互联网 发布:医疗大数据盈利模式 编辑:程序博客网 时间:2024/06/01 08:54

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.


var canConstruct = function(r, m) {
    if(r.length > m.length) {
        return false
    }
    if(r.length == m.length && r != m){
        return false
    }
    var obj = {};
    for(var i = 0; i < m.length; i++) {
        if(!obj[m[i]]){
            obj[m[i]] = 1
        }else{
            obj[m[i]] ++;
        }
    }
    for(var j = 0; j < r.length; j++) {
        if(obj[r[j]] && obj[r[j]] >= 0) {
            obj[r[j]] -- ;
        }else{
            return false
        }
    }
    return true
};

0 0
原创粉丝点击