查找并输出字符串中出现次数最多的字母和出现的次数
偶然看到这道题,觉得出现频率挺高,貌似经常考,自己试着写了一遍,貌似看着有点不优雅,欢迎高手指教~
//思路: 1.数组先排序
// 2.两组指针,一组指针记录历史次数最多字母及次数,一组指针记录当前字母及出现次数
getA() {
let a = 'sfgsdufegfvuidsvbeaaaaaaaaaiyvgsdfaaaasdassdshdashhbsdjghiuyhhg';
let arr = Array.from(a).sort();
let maxCount = 0,maxString = arr[0],currentCount = 1,currentString = arr[0];
arr.forEach((v,i) => {
currentString = v;
if(v === arr[i+1]){
currentCount++;
}else{
if(maxCount < currentCount){
maxCount = currentCount;
maxString = currentString;
}else if(maxCount == currentCount){
if(typeof maxString === 'string'){
maxString = Array.from(maxString)
maxString.push(currentString);
}else maxString.push(currentString)
}
currentCount = 1;
}
})
return typeof maxString === 'string' ? [maxString,maxCount] : [maxString.join(' '),maxCount]
}
// 输出方式具体看题目要求
console.log(...getA());