Counting substrings of a string that contains only one distinct letter in JavaScript


We are required to write a JavaScript function that takes in a string as the only argument. The task of our function is to count all the contiguous substrings in the input string that contains exactly one distinct letter.

The function should then return the count of all such substrings.

For example −

If the input string is −

const str = 'iiiji';

Then the output should be −

const output = 8;

because the desired strings are −

'iii', 'i', 'i', 'i', 'i', 'j', 'ii', 'ii'

Example

Following is the code −

const str = 'iiiji';
const countSpecialStrings = (str = '') => {
   let { length } = str;
   let res = length;
   if(!length){
      return length;
   };
   for (let j = 0, i = 1; i < length; ++ i) {
      if (str[i] === str[j]) {
         res += i - j;
      } else {
         j = i;
      }
   };
   return res;
}
console.log(countSpecialStrings(str));

Output

Following is the console output −

8

Updated on: 20-Jan-2021

143 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements