主题
js字符串字符出现最大次数并统计次数的三种方法
第一种
javascript
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"));第二种
javascript
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"));第三种
javascript
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"));