Count of substrings of a given Binary string with all characters same | 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
def countSubAllOnes ( s ) : NEW_LINE INDENT l , r , ans = 0 , 0 , 0 NEW_LINE while ( l <= r ) : NEW_LINE INDENT if ( r == len ( s ) ) : NEW_LINE INDENT ans += ( ( r - l ) * ( r - l + 1 ) ) // 2 NEW_LINE break NEW_LINE DEDENT if ( s [ r ] == '1' ) : NEW_LINE INDENT r += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += ( ( r - l ) * ( r - l + 1 ) ) // 2 NEW_LINE l = r + 1 NEW_LINE r += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def flip ( s ) : NEW_LINE INDENT arr = list ( s ) NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( arr [ i ] == '1' ) : NEW_LINE INDENT arr [ i ] = '0' NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = '1' NEW_LINE DEDENT DEDENT s = ' ' . join ( arr ) NEW_LINE return s NEW_LINE DEDENT def countSubAllZerosOnes ( s ) : NEW_LINE INDENT only_1s = countSubAllOnes ( s ) NEW_LINE s = flip ( s ) NEW_LINE only_0s = countSubAllOnes ( s ) NEW_LINE return only_0s + only_1s NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "011" NEW_LINE print ( countSubAllZerosOnes ( s ) ) NEW_LINE DEDENT