class RepeatStr {
constructor(str) {
this.str = str;
this.resultObj = {};
this.resultArray = [];
this.maxNumber = null;
this.elArray = null;
}
getStrArr() {
return this.str.split('').reduce(function (prev, next) {
prev[next] = (prev[next] + 1) || 1;
return prev;
}, {});
}
getRepeatStrArr() {
this.resultObj = this.getStrArr();
for (let key in this.resultObj) {
this.resultArray.push({[key]: this.resultObj[key]})
}
}
getElArr() {
this.getRepeatStrArr();
this.maxNumber = Math.max.apply(null, Object.values(this.resultObj))
this.elArray = this.resultArray.filter(e => {
let key = Object.keys(e)[0];
return e[key] === this.maxNumber;
})
}
output() {
this.getElArr();
let str = '', num;
if (!this.elArray.length) {
console.log('字符串为空');
return;
}
this.elArray.forEach(e => {
let key = Object.keys(e)[0];
str += key + ','
num = e[key]
})
console.log(`出现次数最多的字符是${str} 出现次数是${num}次`)
}
}
new RepeatStr('dsajkldsalkjdsaazzz2222').output();
网友评论