一个非空字符串,计算出现次数最多的字符,返回该字符及出现次数,结果可能包含多个字符。如传入“xyzzyxyz”,则返回:{y:3, z:3}
function maxString(str){
var arr = str.split("");
var obj = {};
var obj2 = {};
var max = 1;
for (let i = 0; i < arr.length; i++) {
var item = arr[i];
obj[item] = (obj[item]+1) || 1;
}
for (var key in obj) {
if(obj[key]>max){
max = obj[key];
}
}
for(var key in obj){
if(obj[key] === max){
obj2[key] = max;
}
}
return obj2;
}
console.log(maxString('3uu7zzzyzzpuuu'));//{u: 5, z: 5}
判断一个字符串中出现次数最多的字符,统计这个次数
function maxSub(str){
var json = {};
for (var i = 0; i < str.length; i++) {
if(!json[str.charAt(i)]){
json[str.charAt(i)] = 1;
}else{
json[str.charAt(i)]++;
}
};
var iMax = 0;
var iIndex = '';
for(var i in json){
if(json[i]>iMax){
iMax = json[i];
iIndex = i;
}
}
var result = '出现次数最多的是:'+iIndex+'出现'+iMax+'次';
return result
}
console.log(maxSub('78uuye63u'))
网友评论