text: Count number of substrings of a string consisting of same characters | C ++ implementation of the above approach ; Function to return the number of substrings of same characters ; Size of the string ; Initialize count to 1 ; Initialize left to 0 and right to 1 to traverse the string ; Checking if consecutive characters are same and increment the count ; When we encounter a different characters ; Increment the result ; To repeat the whole process set left equals right and count variable to 1 ; Store the final value of result ; Driver code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void findNumbers ( string s ) { if ( s . empty ( ) ) return 0 ; int n = s . size ( ) ; int count = 1 ; int result = 0 ; int left = 0 ; int right = 1 ; while ( right < n ) { if ( s [ left ] == s [ right ] ) { count ++ ; } else { result += count * ( count + 1 ) / 2 ; left = right ; count = 1 ; } right ++ ; } result += count * ( count + 1 ) / 2 ; cout << result << endl ; } int main ( ) { string s = " bbbcbb " ; findNumbers ( s ) ; }