Find an equal point in a string of brackets | Method to find an equal index ; Store the number of opening brackets at each index ; Store the number of closing brackets at each index ; check if there is no opening or closing brackets ; check if there is any index at which both brackets are equal ; Driver Code
def findIndex ( str ) : NEW_LINE INDENT l = len ( str ) NEW_LINE open = [ 0 ] * ( l + 1 ) NEW_LINE close = [ 0 ] * ( l + 1 ) NEW_LINE index = - 1 NEW_LINE open [ 0 ] = 0 NEW_LINE close [ l ] = 0 NEW_LINE if ( str [ 0 ] == ' ( ' ) : NEW_LINE INDENT open [ 1 ] = 1 NEW_LINE DEDENT if ( str [ l - 1 ] == ' ) ' ) : NEW_LINE INDENT close [ l - 1 ] = 1 NEW_LINE DEDENT for i in range ( 1 , l ) : NEW_LINE INDENT if ( str [ i ] == ' ( ' ) : NEW_LINE INDENT open [ i + 1 ] = open [ i ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT open [ i + 1 ] = open [ i ] NEW_LINE DEDENT DEDENT for i in range ( l - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( str [ i ] == ' ) ' ) : NEW_LINE INDENT close [ i ] = close [ i + 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT close [ i ] = close [ i + 1 ] NEW_LINE DEDENT DEDENT if ( open [ l ] == 0 ) : NEW_LINE INDENT return len NEW_LINE DEDENT if ( close [ 0 ] == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT for i in range ( l + 1 ) : NEW_LINE INDENT if ( open [ i ] == close [ i ] ) : NEW_LINE INDENT index = i NEW_LINE DEDENT DEDENT return index NEW_LINE DEDENT str = " ( ( ) ) ) ( ( ) ( ) ( ) ) ) ) " NEW_LINE print ( findIndex ( str ) ) NEW_LINE