Minimum number of bracket reversals needed to make an expression balanced | Java 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 method
import java . util . Stack ; public class GFG { static int countMinReversals ( String expr ) { int len = expr . length ( ) ; if ( len % 2 != 0 ) return - 1 ; Stack < Character > s = new Stack < > ( ) ; for ( int i = 0 ; i < len ; i ++ ) { char c = expr . charAt ( i ) ; if ( c == ' } ' && ! s . empty ( ) ) { if ( s . peek ( ) == ' { ' ) s . pop ( ) ; else s . push ( c ) ; } else s . push ( c ) ; } int red_len = s . size ( ) ; int n = 0 ; while ( ! s . empty ( ) && s . peek ( ) == ' { ' ) { s . pop ( ) ; n ++ ; } return ( red_len / 2 + n % 2 ) ; } public static void main ( String [ ] args ) { String expr = " } } { { " ; System . out . println ( countMinReversals ( expr ) ) ; } }