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 ; Expressions of odd lengths cannot be balanced ; If we find a left bracket then we simply increment the left bracket ; Else if left bracket is 0 then we find unbalanced right bracket and increment right bracket or if the expression is balanced then we decrement left ; Driver method
import java . util . * ; public class GFG { static int countMinReversals ( String expr ) { int len = expr . length ( ) ; int ans ; if ( len % 2 != 0 ) { return - 1 ; } int left_brace = 0 , right_brace = 0 ; for ( int i = 0 ; i < len ; i ++ ) { char ch = expr . charAt ( i ) ; if ( ch == ' { ' ) { left_brace ++ ; } else { if ( left_brace == 0 ) { right_brace ++ ; } else { left_brace -- ; } } } ans = ( int ) ( Math . ceil ( ( 0.0 + left_brace ) / 2 ) + Math . ceil ( ( 0.0 + right_brace ) / 2 ) ) ; return ans ; } public static void main ( String [ ] args ) { String expr = " } } { { " ; System . out . println ( countMinReversals ( expr ) ) ; } }