Count substrings made up of a single distinct character | C ++ program for the above approach ; Function to count the number of substrings made up of a single distinct character ; Stores the required count ; Stores the count of substrings possible by using current character ; Stores the previous character ; Traverse the string ; If current character is same as the previous character ; Increase count of substrings possible with current character ; Reset count of substrings possible with current character ; Update count of substrings ; Update previous character ; Driver code
#include <iostream> NEW_LINE using namespace std ; void countSubstrings ( string s ) { int ans = 0 ; int subs = 1 ; char pre = '0' ; for ( auto & i : s ) { if ( pre == i ) { subs += 1 ; } else { subs = 1 ; } ans += subs ; pre = i ; } cout << ans << endl ; } int main ( ) { string s = " geeksforgeeks " ; countSubstrings ( s ) ; return 0 ; }