Minimum Number of Swaps to Make the String Balanced LeetCode solution in Java

1
class Solution {
2
public int minSwaps(String s) {
3
// remove the balanced part from the given string
4
Stack<Character> stack = new Stack<>();
5
for (char ch : s.toCharArray()) {
6
if (ch == '[') stack.push(ch);
7
else {
8
if (!stack.isEmpty() && stack.peek() == '[') stack.pop();
9
else stack.push(ch);
10
}
11
}
12
int unb = stack.size() / 2; // # of open or close bracket
13
return (unb + 1) / 2;
14
}
15
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0