主题
找出字符串出现最多次数的字符以及次数
方式一:
var str = 'aaabbbbbccddddddddddx';
var obj = {};
for(var i=0;i<str.length;i++){
var char = str.charAt(i);
if( obj[char] ){
obj[char]++;
}else{
obj[char] = 1;
}
}
console.log( obj );
//统计出来最大值
var max = 0;
for( var key in obj ){
if( max < obj[key] ){
max = obj[key];
}
}
//拿最大值去对比
for( var key in obj ){
if( obj[key] == max ){
console.log('最多的字符是'+key);
console.log('出现的次数是'+max);
}
}方式二:new Map
const fun = (str) => {
let map = new Map();
let maxValue = '';
let maxNum = 0;
for (let item of str) {
map.set(item, (map.get(item) || 0) + 1)
}
for (let [key, value] of map) {
if (value > maxNum) {
maxValue = key;
maxNum = value
}
}
return [maxValue, maxNum]
}
console.log(fun('abcabcabccc'))方式三:for-of/for-in
const fun = (str) => {
let obj = {};
let maxValue = '';
let maxNum = 0;
for (let key of str) {
obj[key] = !obj[key] ? 1 : obj[key] + 1
}
for (let key in obj) {
if (obj[key] > maxNum) {
maxValue = key;
maxNum = obj[key]
}
}
return [maxValue, maxNum]
}
console.log(fun('abcabcabccc'))方式四:正则
const fun = (str) => {
//出现次数字符最多
let maxValue = '';
//出现次数字符最多的数字
let maxNum = 0;
//排序
str=str.split("").sort().join("")
//正则匹配
let reg=/(\w)\1+/g;
str.replace(reg, (val,item)=>{
if(val.length>maxNum){
maxNum=val.length
maxValue=item
}
})
console.log(str.match(reg))
return [maxValue, maxNum]
}
console.log(fun('abcabcabccc'))