Minimum swaps to balance the given brackets at any index | Java implementation for the above approach ; Function to balance the given bracket by swap ; To count the number of uunbalanced pairs ; if there is an opening bracket and we encounter closing bracket then it will decrement the count of unbalanced bracket . ; else it will increment unbalanced pair count ; Driver code
import java . io . * ; import java . util . * ; class GFG { static int BalancedStringBySwapping ( String s ) { int unbalancedPair = 0 ; for ( int i = 0 ; i < s . length ( ) ; ++ i ) { if ( unbalancedPair > 0 && s . charAt ( i ) == ' ] ' ) { -- unbalancedPair ; } else if ( s . charAt ( i ) == ' [ ' ) { ++ unbalancedPair ; } } return ( unbalancedPair + 1 ) / 2 ; } public static void main ( String [ ] args ) { String s = " ] ] ] [ [ [ " ; System . out . println ( BalancedStringBySwapping ( s ) ) ; } }