How to get the maximum count of repeated letters in a string? JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We have a string that contains some repeated letters like this −

const a = "fdsfjngjkdsfhhhhhhhhhhhfsdfsd";

Our job is to write a function that returns the count of maximum consecutive same letters in a streak. Like in the above string the letter h appears for 11 times in a row consecutively, so our function should return 11 for this string.

This problem is a good candidate for this sliding window algorithm, here a stable window will be the one that contains consecutive letters and one that contains different elements is unstable. The window tends to get stable by adding new letters at the end and removing repetitive letters at the start.

The code for this function that uses sliding window algorithm will be −

Example

const a = "fdsfjngjkdsfhhhhhhhhhhhfsdfsd";
const findMaximumRepeating = str => {
   let max = 0;
   for(let start = 0, end = 1; end < str.length; ){
      if(str[end] === str[start]){
         if(max < end - start + 1){
            max = end - start + 1;
         };
         end++;
      } else {
         start = end;
      };
   };
   return max;
};
console.log(findMaximumRepeating(a));

Output

The output in the console will be −

11
raja
Published on 28-Aug-2020 17:08:43
Advertisements