Home  >  Article  >  Web Front-end  >  JavaScript implements counting the most frequent characters and the number of occurrences in a string_javascript skills

JavaScript implements counting the most frequent characters and the number of occurrences in a string_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:09:571118browse

"Calculate what character appears most often in the string and how many times it appears?"

Seeing this demand, I think the first thing most people should think of is to convert it into an array and then process it. Of course, the problem can be solved. Then here is an ingenious algorithm design that can be solved quickly without converting into an array. Question, the code is as follows:

Copy code The code is as follows:

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);
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn