javascript gets the character with the most repetitions

  • 2020-07-21 06:46:54
  • OfStack

javascript gets the character with the most repetitions


/**
   Retrieves the character with the most repeated words in the string 
*/
var words = 'sdfghjkfastgbyhnvdstyaujskgfdfhlaa';       // Create a string 
var word,                           // A single character 
  length;                          // The length of the character 
// Define the output object 
var max = {
  wordName : '',                      // The character with the most repetitions 
  wordLength : 0                      // Number of repetitions 
};
// Recursive method , Pass in a string 
(function(words) {
  if (!words) return;         // Returns if the string has been nulled , End of the recursive 
  word  = words[0];         // Fetch the first in the string 1 A character 
  length = words.length;         // will length Set to the current string length 
  words  = words.replace(new RegExp(word, 'g'), ''); // Returns the remaining string that removes the current character from the string 
  length = length - words.length;      // reset length Is the length of the current character in the string 
  if (length > max.wordLength)       // If the character is repeated more than once maxLength, The reset maxLength Is the number of current character repeats 
    max = {               // Resets the value of the object 
      wordName  : word,            
      wordLength : length       
    };              
  arguments.callee(words);        // Recursive calls , Pass in the remaining string 
})(words);
console.log(max.wordName+"\n"+max.wordLength);     // Output the result when the recursion ends 
  

I happened to see such a problem this morning. I saw that most of the Internet is made with two loops. Then I recursively wrote 1

Idea is to

Take the first character. Remove the character of the same symbol from the string, and take the previous string length minus the deleted string length.

The result is the number of repetitions of the current character in the string.

Determines if the character is more repeated than maxLength stored in the current output object.

As in true, updated

It then recurses until the string is replaced and terminates

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

This is the end of this article, I hope you enjoy it.


Related articles: