Count of substrings of a given Binary string with all characters same | Java 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
import java . util . * ; class GFG { static 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 . charAt ( r ) == '1' ) r ++ ; else { ans += ( ( r - l ) * ( r - l + 1 ) ) / 2 ; l = r + 1 ; r ++ ; } } return ans ; } static String flip ( char [ ] s ) { for ( int i = 0 ; i < s . length ; i ++ ) { if ( s [ i ] == '1' ) s [ i ] = '0' ; else s [ i ] = '1' ; } return String . valueOf ( s ) ; } static int countSubAllZerosOnes ( String s ) { int only_1s = countSubAllOnes ( s ) ; s = flip ( s . toCharArray ( ) ) ; int only_0s = countSubAllOnes ( s ) ; return only_0s + only_1s ; } public static void main ( String [ ] args ) { String s = "011" ; System . out . print ( countSubAllZerosOnes ( s ) + "NEW_LINE"); } }