Minimum Swaps for Bracket Balancing | Java program to count swaps required to balance string ; Function to calculate swaps required ; Keep track of ' [ ' ; To count number of encountered ' [ ' ; To track position of next ' [ ' in pos ; To store result ; Increment count and move p to next position ; We have encountered an unbalanced part of string ; Increment sum by number of swaps required i . e . position of next ' [ ' - current position ; Reset count to 1 ; Driver code
import java . util . * ; class GFG { public static long swapCount ( String s ) { Vector < Integer > pos = new Vector < Integer > ( ) ; for ( int i = 0 ; i < s . length ( ) ; ++ i ) if ( s . charAt ( i ) == ' [ ' ) pos . add ( i ) ; int count = 0 ; int p = 0 ; long sum = 0 ; char [ ] S = s . toCharArray ( ) ; for ( int i = 0 ; i < s . length ( ) ; ++ i ) { if ( S [ i ] == ' [ ' ) { ++ count ; ++ p ; } else if ( S [ i ] == ' ] ' ) -- count ; if ( count < 0 ) { sum += pos . get ( p ) - i ; char temp = S [ i ] ; S [ i ] = S [ pos . get ( p ) ] ; S [ pos . get ( p ) ] = temp ; ++ p ; count = 1 ; } } return sum ; } public static void main ( String [ ] args ) { String s = " [ ] ] [ ] [ " ; System . out . println ( swapCount ( s ) ) ; s = " [ [ ] [ ] ] " ; System . out . println ( swapCount ( s ) ) ; } }