Balance a string after removing extra brackets | Java implementation of above approach ; Print balanced and remove extra brackets from string ; Maintain a count for opening brackets Traversing string ; check if opening bracket ; print str . charAt ( i ) and increment count by 1 ; check if closing bracket and count != 0 ; decrement count by 1 ; if str . charAt ( i ) not a closing brackets print it ; balanced brackets if opening brackets are more then closing brackets ; print remaining closing brackets ; Driver Method
class GFG { public static void balancedString ( String str ) { int count = 0 , i ; int n = str . length ( ) ; for ( i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) == ' ( ' ) { System . out . print ( str . charAt ( i ) ) ; count ++ ; } else if ( str . charAt ( i ) == ' ) ' && count != 0 ) { System . out . print ( str . charAt ( i ) ) ; count -- ; } else if ( str . charAt ( i ) != ' ) ' ) System . out . print ( str . charAt ( i ) ) ; } if ( count != 0 ) for ( i = 0 ; i < count ; i ++ ) System . out . print ( " ) " ) ; } public static void main ( String args [ ] ) { String str = " gau ) ra ) v ( ku ( mar ( rajput ) ) " ; balancedString ( str ) ; } }