

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Questions & Answers
- Counting matching substrings in JavaScript
- How to check if a string contains only one type of character in R?
- Counting even decimal value substrings in a binary string in C++
- Counting the number of palindromes that can be constructed from a string in JavaScript
- Convert given string so that it holds only distinct characters in C++
- Segregating a string into substrings - JavaScript
- Counting number of vowels in a string with JavaScript
- Get all substrings of a string in JavaScript recursively
- Distinct Echo Substrings in C++
- Program to find out number of distinct substrings in a given string in python
- Repeating letter string - JavaScript
- Make first letter of a string uppercase in JavaScript?
- Section that contains only navigation links in HTML5
- Finding missing letter in a string - JavaScript
- How to reverse a string using only one variable in JavaScript
Advertisements