Minimum Number of Swaps to Make the String Balanced LeetCode solution in C++
1class Solution {2public:3int minSwaps(string s) {4int ans = 0;5stack<char> stack;6for (int i = 0; i < s.length(); i++) {7if (s[i] == '[') {8stack.push(s[i]);9}10if (s[i] == ']' && stack.size() != 0 && stack.top() == '[') {11stack.pop();12}13}1415ans = stack.size();16if (ans % 2 == 0)17return ans / 2;18else19return (ans + 1) / 2;20}21};