Train of thought

  1. You can save the first of each string beginning with a repeated letter into a variable (in code)a), and then compare the following array elements to it:
  • If the same, the counter is accumulated. The counter represents the length of the repeated string
  • If not, a new letter is followed and the variable needs to be updateda, and record the subscript of the string array (used to intercept the end of the repeated string), and finally determine whether to update according to the length of the repeated stringmaxStrThe value of the.
  1. In order to avoid the possibility that two strings of repeated letters are of equal length, we can declare an alternate string in advance (in the code)maxStrl). Finally, check whether the above situation occurs according to whether the length of the backup string is 0:
  • If it does, it needs to be printed simultaneouslymaxStrandmaxStrlThe content of the
  • If it doesn’t, just print itmaxStrYou can

Alternatively, you can print two parts of the content directly together, and it doesn’t matter if maxStrl is empty.

    <script>
        maxr("mmmiijjjjkkkkkkssptr");

        function maxr(char){
            var arr = char.split("");
            var maxCount=0;
            var maxStr = "";
            var maxStrl = ""; // If there are two strings of the same length, store the other one as a backup
            var a; //a is used to represent the current letter
            a = arr[0]; / / initialization
            // Intercepts a string
            var end;

            for(var i=0; i<arr.length; i++){if(arr[i] == a){

                    maxCount += 1;
                }
                else {
                    end = i;
                    // console.log(maxCount);
                    var maxStr1 = char.slice(end-maxCount,end);
                    // console.log(maxStr);

                    // Determine if it is the largest
                    if(maxStr1.length > maxStr.length){
                        maxStr = maxStr1;
                    }
                    // If there are two parts of equal length
                    else if (maxStr1.length == maxStr.length){
                        maxStrl = maxStr1;
                    }

                    a = arr[i];
                    maxCount = 1; }}// Determine the result output
            if(maxStrl.length == 0) {console.log(maxStr);
                    }
                    else{
                        console.log(maxStr);
                        console.log(maxStrl); }}</script>

Copy the code

Output:

kkkkkk
Copy the code