
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 with 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
Advertisements