1,要求:求字符串出现最多次数的字母;输出字母和对应的次数;
如: str = 'aaaaadabbbbbbccccdcc';
要求出 str 中 a b c d 谁出现的次数多;
思路: 求出每个字母出现的次数,并比较出现最多的;
可以自己先实现一下,看看跟最后有什么区别;
首先要知道 str 中 出现了什么字母;因为字符串是不确定的 有可能 str ='dddsdfejfsdlkfje' 很随意;
所以 实现步骤应该为:
字符串要转为数组,去重;(求出所有出现的字母)
然后统计每个字母出现的次数;
比较出出现最多次数的那个;
function getStr(str){
var str = str.split('');
var newStr = {};
var theMax = 0;
// 数组去重 和计算出现的次数
str.forEach(function(item){
if(newStr[item]){
newStr[item]++;
}else {
newStr[item] = 1;
}
});
// 比较字母出现的次数,并取出出现最多次数的字母及对应的次数;
for(str in newStr){
if(newStr[str] > theMax){
// 注意点 [1] 这里是避免出现 多个字母出现相同次数的情况
// 如果 var maxStr = [] 不在for 内的话效果会有问题 ,可以放在if 外
var maxStr =[];
theMax = newStr[str];
maxStr.push(str);
}else if(newStr[str] == theMax){
theMax = newStr[str];
maxStr.push(str);
}
}
// 输出方式随意
console.log('以下字母出现次数最多,出现次数为:'+theMax +'次');
for(var i= 0;i<maxStr.length;i++){
console.log(maxStr[i]);
}
}
var testStr = 'qqqwwwaaaaa9dfdfs999999999d';
getStr(testStr);
之所以写这个,是因为一开始;
去重 用的是 forEach();
跟 统计每个字母出现的次数;
分成两步完成,用了两个循环;
后面再百度上看到百度上去重统计的方法,觉得很简单(思路很重要);
注意点【1】中,因为字符串可能出现 不同字母出现同样次数状况,如: str = ‘aaaa,bbbb,ccccccc,dddddddd’;
这样 如果var maxStr = []; 在for 外面的话a,b,c,d ,都会被存到 maxStr 中,所以 每次 if 成立的最大值 都要重新 var 一下 maxStr;
在if 里面或if 外面,for里面 运行的结果:
在 for 外面运行的结果
再小的demo 也是有逻辑在里面的。思考!!!