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
function balancedString ( str ) { var count = 0 , i ; var n = str . length ; for ( i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' ' ) { document . write ( str [ i ] ) ; count ++ ; } else if ( str [ i ] == ' ' && count != 0 ) { document . write ( str [ i ] ) ; count -- ; } else if ( str [ i ] != ' ' ) document . write ( str [ i ] ) ; } if ( count != 0 ) for ( i = 0 ; i < count ; i ++ ) document . write ( " " ) ; } var str = " " ; balancedString ( str ) ;