返回字符串中字符出现次数最多的那字符

原创 1130331201 随笔 JS算法 104阅读 2018-01-31 11:19:11 举报

var str = "abbcccddddfffffgggggg";

function maxNum(str){

    if(str.length <= 1){
        return str;
    }

    var a1 = str.split(''),obj = {},result = [];
    //利用上面一个数组去重的思想
    for(var k = 0, l = a1.length; k < l; k++){
        if(!obj[a1[k]]){
            obj[a1[k]] = 1;
        }else {
            obj[a1[k]] += 1;
        };
    }

    var num = 0, word = "";
    for(var item in obj){
        if(obj[item] > num){
            num = obj[item];
            word = item;
        }
    }
    return word;
}
var w = maxNum(str);
console.log(w);   //g
评论 ( 0 )
最新评论
暂无评论

赶紧努力消灭 0 回复