Length of the longest substring with equal 1 s and 0 s | Function to check if a contains equal number of one and zeros or not ; Function to find the length of the longest balanced substring ; Driver code ; Function call
def isValid ( p ) : NEW_LINE INDENT n = len ( p ) NEW_LINE c1 = 0 NEW_LINE c0 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( p [ i ] == '0' ) : NEW_LINE INDENT c0 += 1 NEW_LINE DEDENT if ( p [ i ] == '1' ) : NEW_LINE INDENT c1 += 1 NEW_LINE DEDENT DEDENT if ( c0 == c1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def longestSub ( s ) : NEW_LINE INDENT max_len = 0 NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT if ( isValid ( s [ i : j - i + 1 ] ) and max_len < j - i + 1 ) : NEW_LINE INDENT max_len = j - i + 1 NEW_LINE DEDENT DEDENT DEDENT return max_len NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "101001000" NEW_LINE print ( longestSub ( s ) ) NEW_LINE DEDENT