Minimum number of bracket reversals needed to make an expression balanced | Set | Java program to find minimum number of reversals required to balance an expression ; Returns count of minimum reversals for making expr balanced . Returns - 1 if expr cannot be balanced . ; length of expression must be even to make it balanced by using reversals . ; To store number of reversals required . ; To store number of unbalanced opening brackets . ; To store number of unbalanced closing brackets . ; If current bracket is open then increment open count . ; If current bracket is close , check if it balances opening bracket . If yes then decrement count of unbalanced opening bracket else increment count of closing bracket . ; For the case : " } { " or when one closing and one opening bracket remains for pairing , then both need to be reversed . ; Driver Code
class GFG { static int countMinReversals ( String expr ) { int len = expr . length ( ) ; if ( len % 2 != 0 ) return - 1 ; int ans = 0 ; int i ; int open = 0 ; int close = 0 ; for ( i = 0 ; i < len ; i ++ ) { if ( expr . charAt ( i ) == ' { ' ) open ++ ; else { if ( open == 0 ) close ++ ; else open -- ; } } ans = ( close / 2 ) + ( open / 2 ) ; close %= 2 ; open %= 2 ; if ( close != 0 ) ans += 2 ; return ans ; } public static void main ( String args [ ] ) { String expr = " } } { { " ; System . out . println ( countMinReversals ( expr ) ) ; } }