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

1
class Solution {
2
public:
3
int minSwaps(string s) {
4
int ans = 0;
5
stack<char> stack;
6
for (int i = 0; i < s.length(); i++) {
7
if (s[i] == '[') {
8
stack.push(s[i]);
9
}
10
if (s[i] == ']' && stack.size() != 0 && stack.top() == '[') {
11
stack.pop();
12
}
13
}
14

15
ans = stack.size();
16
if (ans % 2 == 0)
17
return ans / 2;
18
else
19
return (ans + 1) / 2;
20
}
21
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0