text: Minimum Swaps for Bracket Balancing | C # 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
code: using System . IO ; using System ; using System . Collections ; using System . Collections . Generic ; class GFG { static long swapCount ( string s ) { List < int > pos = new List < int > ( ) ; for ( int i = 0 ; i < s . Length ; i ++ ) { if ( s [ 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 [ p ] - i ; char temp = S [ i ] ; S [ i ] = S [ pos [ p ] ] ; S [ pos [ p ] ] = temp ; ++ p ; count = 1 ; } } return sum ; } static void Main ( ) { string s = " [ ] ] [ ] [ " ; Console . WriteLine ( swapCount ( s ) ) ; s = " [ [ ] [ ] ] " ; Console . WriteLine ( swapCount ( s ) ) ; } }