Finding the power of a string from a string with repeated letters in JavaScript


The power of the string is the maximum length of a non−empty substring that contains only one unique character.

We are required to write a JavaScript function that takes in a string and returns its power.

For example −

const str = "abbcccddddeeeeedcba"

Then the output should be 5,

because the substring "eeeee" is of length 5 with the character 'e' only.

Example

The code for this will be −

const str = "abbcccddddeeeeedcba"
const maxPower = (str = '') => {
   let power = 1
   const sz = str.length - 1
   for(let i = 0; i < sz; ++i) {
      let count = 1
      while(i < sz && str[i + 1] === str[i] && ++i)
      power = Math.max(power, ++count)
   }
   return power
};
console.log(maxPower(str));

Output

And the output in the console will be −

5

Updated on: 20-Nov-2020

418 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements