text: Minimum number of bracket reversals needed to make an expression balanced | C # Code to count minimum reversal for making an expression balanced . ; Method count minimum reversal for making an expression balanced . Returns - 1 if expression cannot be balanced ; length of expression must be even to make it balanced by using reversals . ; After this loop , stack contains unbalanced part of expression , i . e . , expression of the form " } } . . } { { . . { " ; Length of the reduced expression red_len = ( m + n ) ; count opening brackets at the end of stack ; return ceil ( m / 2 ) + ceil ( n / 2 ) which is actually equal to ( m + n ) / 2 + n % 2 when m + n is even . ; Driver Code
code: using System ; using System . Collections . Generic ; class GFG { public static int countMinReversals ( string expr ) { int len = expr . Length ; if ( len % 2 != 0 ) { return - 1 ; } Stack < char > s = new Stack < char > ( ) ; for ( int i = 0 ; i < len ; i ++ ) { char c = expr [ i ] ; if ( c == ' } ' && s . Count > 0 ) { if ( s . Peek ( ) == ' { ' ) { s . Pop ( ) ; } else { s . Push ( c ) ; } } else { s . Push ( c ) ; } } int red_len = s . Count ; int n = 0 ; while ( s . Count > 0 && s . Peek ( ) == ' { ' ) { s . Pop ( ) ; n ++ ; } return ( red_len / 2 + n % 2 ) ; } public static void Main ( string [ ] args ) { string expr = " } } { { " ; Console . WriteLine ( countMinReversals ( expr ) ) ; } }