The JavaScript implementation counts the most frequently occurring characters in a string and the number of occurrences

  • 2020-05-16 06:17:22
  • OfStack

"Figure out what character appears the most in a string, and how many times?"

Seeing this requirement, I think most people should first think of converting to an array and then doing some processing. Of course, it can solve the problem. Then, here is a clever algorithm design, which can solve the problem quickly without converting to an array.


var str = "adadfdfseffserfefsefseeffffftsdg";
var maxLength = 0;
var result = "";
while(str!=''){
    oldStr = str;
    getStr = str.charAt(0);
    str = str.replace(new RegExp(getStr,"g"),"");
    if( oldStr.length-str.length > maxLength){
        maxLength = oldStr.length-str.length;
        result = getStr + "=" + maxLength;
    }
}
alert(result);


Related articles: