Javascript gets the most repeated characters and the number of javascript times
Javascript obtains the most repeated characters
/** Extract the characters with the most repeated words in the string */var words = 'sdfghjkfastgbyhnvdstyaujskgfdfhlaa'; // create the string var word, // length of a single character; // The length of this character // defines the output object var max = {wordName: '', // wordLength: 0 // repeated times }; // recursive method, passed in the string (function (words) {if (! Words) return; // If the string has become null, return, end recursion word = words [0]; // retrieve the first character in the string length = words. length; // set the length to the current String length of words = words. replace (new RegExp (word, 'G'), ''); // returns the remaining String length = length-words that removes the current character. length; // reset the length to the length of the current character in the string if (length> max. wordLength) // if the number of repetitions of this character is greater than maxLength, set maxLength to the number of repetitions of the current character max ={// reset the value of the object wordName: word, wordLength: length }; arguments. callee (words); // recursive call, pass in the remaining string}) (words); console. log (max. wordName + "\ n" + max. wordLength); // output after Recursion
This morning, I accidentally saw this problem. I saw that most of the Internet was made out of two loops. Then I wrote it recursively.
The idea is
Each recursion. Extract the first character. Remove the characters with the same symbol from the string, and subtract the length of the removed string from the previous string.
The number of times the current character in the string is repeated.
Determines whether the number of repeated characters is greater than the maxLength stored in the current output object.
If true, update
Then go to the next recursion until the string is replaced and terminated.
The output object stores the most frequently used characters and repeated times.
The above is all the content of this article. I hope you will like it.