Count of substrings of a given Binary string with all characters same | C ++ program for the above approach ; Function to count number of sub - strings of a given binary string that contains only 1 ; Iterate untill L and R cross each other ; Check if reached the end of string ; Check if encountered '1' then extend window ; Check if encountered '0' then add number of strings of current window and change the values for both l and r ; Return the answer ; Function to flip the bits of string ; Function to count number of sub - strings of a given binary string that contains only 0 s & 1 s ; count of substring which contains only 1 s ; Flip the character of string s 0 to 1 and 1 to 0 to count the substring with consecutive 0 s ; count of substring which contains only 0 s ; Driver Code ; Given string str ; Function Call
#include <iostream> NEW_LINE using namespace std ; int countSubAllOnes ( string s ) { int l = 0 , r = 0 , ans = 0 ; while ( l <= r ) { if ( r == s . length ( ) ) { ans += ( ( r - l ) * ( r - l + 1 ) ) / 2 ; break ; } if ( s [ r ] == '1' ) r ++ ; else { ans += ( ( r - l ) * ( r - l + 1 ) ) / 2 ; l = r + 1 ; r ++ ; } } return ans ; } void flip ( string & s ) { for ( int i = 0 ; s [ i ] ; i ++ ) { if ( s [ i ] == '1' ) s [ i ] = '0' ; else s [ i ] = '1' ; } cout << s << endl ; } int countSubAllZerosOnes ( string s ) { int only_1s = countSubAllOnes ( s ) ; flip ( s ) ; cout << s << endl ; int only_0s = countSubAllOnes ( s ) ; return only_0s + only_1s ; } int main ( ) { string s = "011" ; cout << countSubAllZerosOnes ( s ) << endl ; return 0 ; }