Minimum Number of Swaps to Make the String Balanced LeetCode solution in Java
1class Solution {2public int minSwaps(String s) {3// remove the balanced part from the given string4Stack<Character> stack = new Stack<>();5for (char ch : s.toCharArray()) {6if (ch == '[') stack.push(ch);7else {8if (!stack.isEmpty() && stack.peek() == '[') stack.pop();9else stack.push(ch);10}11}12int unb = stack.size() / 2; // # of open or close bracket13return (unb + 1) / 2;14}15}