Home  >  Article  >  Web Front-end  >  javascript gets the most repeated characters_javascript tips

javascript gets the most repeated characters_javascript tips

WBOY
WBOYOriginal
2016-05-16 15:50:491257browse

Javascript gets the most repeated characters

/**
  取出字符串中重复字数最多的字符
*/
var words = 'sdfghjkfastgbyhnvdstyaujskgfdfhlaa';       //创建字符串
var word,                           //单个字符
  length;                          //该字符的长度
//定义输出对象
var max = {
  wordName : '',                      //重复次数最多的字符
  wordLength : 0                      //重复的次数
};
//递归方法,传入字符串
(function(words) {
  if (!words) return;         //如果字符串已经变空则返回,结束递归
  word  = words[0];         //取出字符串中的第一个字符
  length = words.length;         //将length设为当前字符串长度
  words  = words.replace(new RegExp(word, 'g'), ''); //返回将字符串剔除当前字符的剩余字符串
  length = length - words.length;      //重设length为当前字符在字符串中的长度
  if (length > max.wordLength)       //如果该字符重复次数大于maxLength,则重设maxLength为当前字符重复次数
    max = {               //重设对象的值
      wordName  : word,            
      wordLength : length       
    };              
  arguments.callee(words);        //递归调用,传入剩余字符串
})(words);
console.log(max.wordName+"\n"+max.wordLength);     //递归结束后输出结果
  

I saw such a problem by chance this morning. I saw that most of the problems on the Internet are made using two loops. Then I wrote it using recursion

The idea is

Each time it recurses, take out the first character. Remove characters with the same symbol from the string, and subtract the length of the removed string from the previous string length.

What is obtained is the number of repetitions of the current character in the string.

Determine whether the number of repetitions of the character is greater than the maxLength stored in the current output object.

If true, update

Then enter the next recursion until the string is replaced and terminate

The output object stores the most frequent characters and the number of repetitions

The above is the entire content of this article, I hope you all like it.

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