Read the most repeated characters from the string and the number of duplicates
Some interview questions directly copied from the Internet always have the following question:
"Please write out the character that reads the most duplicates from the string and the number of duplicates ."
You will find that the solutions available on the Internet are shown in Example 1:
Example 1:
Var strss = adadfdfseffserfefsefseeffffftsdg; // name the string given when a variable is placed.
Var kkk = getMaxStrLength (strss );
Console. log (kkk );
Function getMaxStrLength (str ){
Var maxRepetitionLength = 0;
Var result =;
While (str! = ''){
Var oldStr = str;
Var firstStr = str. substring (0, 1 );
Str = str. replace (new RegExp (firstStr, g ),);
If (oldStr. length-str. length> maxRepetitionLength ){
MaxRepetitionLength = oldStr. length-str. length;
Result = firstStr + = + maxRepetitionLength;
}
}
Return result;
}
I have to say that this type of string is replaced by a space by taking the first character of the string, in addition, the while loop is used to reduce the number of times that the child character appears in the parent and child characters by comparing and removing the length of the character before and after the first character space. The code is very refined and clever. However, I personally feel that reading is not so easy to understand.
Therefore, inspired by the receiver Example 1, we can summarize
Example 2:
Var strs = adadfdfseffserfefsefseeffffftsdg;
Var kk = getMaxStrLength1 (strs );
Console. log (kk );
// Pass each sub-character and parent-child character as the following function parameters through the for loop, and refresh new records continuously through the record parameter maxRepetitionLength
Function getMaxStrLength1 (str ){
Var len = str. length,
Result = '',
MaxRepetitionLength = 0;
For (var I = 0; I Var subStr = str. charAt (I );
Var countArr = countSubstring (str, subStr );
If (countArr [1]> maxRepetitionLength ){
MaxRepetitionLength = countArr [1];
Result = subStr + = + maxRepetitionLength;
}
}
Return result;
}
// Split the function to read the number of times that the subcharacter appears in the parent character
Function countSubstring (str, subString ){
Var count = 0;
Var reg = new RegExp (subString, g );
If (str. match (reg) = null ){
Count = 0;
} Else {
Count = str. match (reg). length;
}
Return [subString, count];
}
Although the above Code is composed of two functions, I personally feel that the function settings are more reasonable. Although the amount of code is more, it is easier to understand.