Minimum Swaps for Bracket Balancing
https://practice.geeksforgeeks.org/problems/minimum-swaps-for-bracket-balancing/0
You are given a string of 2N characters consisting of N ‘[‘ brackets and N ‘]’ brackets. A string is considered balanced if it can be represented in the for S2[S1] where S1 and S2 are balanced strings. We can make an unbalanced string balanced by swapping adjacent characters. Calculate the minimum number of swaps necessary to make a string balanced.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. The first line of each test case contains an integer N denoting the length of the string.
The second line of each test case contains the string consisting of ‘[‘ and ‘]’.
Output:
Print the minimum number of swaps to make the string balanced for each test case in a new line.
Example:
Input : []][][
Output : 2
First swap: Position 3 and 4
[][]][
Second swap: Position 5 and 6
[][][]
Input : [[][]]
Output : 0
String is already balanced.
方法一:每碰到一个 ‘ ] ‘ ,抵消左侧的一个 ‘ [ ‘ ,如果左侧没有 ,则抵消右侧的,此时需要要 swap ,sum += pos(‘ [ ‘) -pos (‘ ] ‘)。但是此时 应回到交换后的 ‘ [ ‘ 重新开始,因为可能已影响到交换前 ‘ ] ‘ 之后符号的决策。
1 |
|
方法二:记录 ‘ ] ‘ 不匹配的个数 imbalance,遇见 ‘ [ ‘ 时,优先配对最远的 ‘ ] ‘,且 imbalance –,依序往下。
1 |
|