Balance a string after removing extra brackets | Print balanced and remove extra brackets from string ; Maintain a count for opening brackets Traversing string ; check if opening bracket ; print str [ i ] and increment count by 1 ; check if closing bracket and count != 0 ; decrement count by 1 ; if str [ i ] not a closing brackets print it ; balanced brackets if opening brackets are more then closing brackets ; print remaining closing brackets ; Driver code
def balancedString ( str ) : NEW_LINE INDENT count , i = 0 , 0 NEW_LINE n = len ( str ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == ' ( ' ) : NEW_LINE INDENT print ( str [ i ] , end = " " ) NEW_LINE count += 1 NEW_LINE DEDENT elif ( str [ i ] == ' ) ' and count != 0 ) : NEW_LINE INDENT print ( str [ i ] , end = " " ) NEW_LINE count -= 1 NEW_LINE DEDENT elif ( str [ i ] != ' ) ' ) : NEW_LINE INDENT print ( str [ i ] , end = " " ) NEW_LINE DEDENT DEDENT if ( count != 0 ) : NEW_LINE INDENT for i in range ( count ) : NEW_LINE INDENT print ( " ) " , end = " " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : str = " gau ) ra ) v ( ku ( mar ( rajput ) ) " NEW_LINE INDENT balancedString ( str ) NEW_LINE DEDENT