Count of sub | C ++ implementation of the above approach ; Function to find the count of substrings with equal no . of consecutive 0 ' s ▁ and ▁ 1' s ; To store the total count of substrings ; Traversing the string ; Count of consecutive 0 ' s ▁ & ▁ 1' s ; Counting subarrays of type "01" ; Count the consecutive 0 's ; If consecutive 0 ' s ▁ ▁ ends ▁ then ▁ check ▁ for ▁ ▁ consecutive ▁ 1' s ; Counting consecutive 1 's ; Counting subarrays of type "10" ; Count consecutive 1 's ; If consecutive 1 ' s ▁ ▁ ends ▁ then ▁ check ▁ for ▁ ▁ consecutive ▁ 0' s ; Count consecutive 0 's ; Update the total count of substrings with minimum of ( cnt0 , cnt1 ) ; Return answer ; Driver code ; Function to print the count of substrings
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubstring ( string & S , int & n ) { int ans = 0 ; int i = 0 ; while ( i < n ) { int cnt0 = 0 , cnt1 = 0 ; if ( S [ i ] == '0' ) { while ( i < n && S [ i ] == '0' ) { cnt0 ++ ; i ++ ; } int j = i ; while ( j < n && S [ j ] == '1' ) { cnt1 ++ ; j ++ ; } } else { while ( i < n && S [ i ] == '1' ) { cnt1 ++ ; i ++ ; } int j = i ; while ( j < n && S [ j ] == '0' ) { cnt0 ++ ; j ++ ; } } ans += min ( cnt0 , cnt1 ) ; } return ans ; } int main ( ) { string S = "0001110010" ; int n = S . length ( ) ; cout << countSubstring ( S , n ) ; return 0 ; }