LeetCode 1541. Minimum Insertions to Balance a Parentheses String

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int minInsertions(string s) {
// c is used to track the diff between the cnt of '(' and '))'.
int n = s.size(), c = 0, ans = 0;
for (int i = 0; i < n; ++i) {
if (s[i] == '(') {
++c; // c should remain nonnegative.
} else {
// if there is no one more ')' available, we need to insert a ')'.
if (i >= n - 1 || s[i + 1] != ')') ++ans;
// or, consume it.
else ++i;
// if there is no enough preceding '(' to match this '))' group, we need to insert a '('.
if (c <= 0) ++ans, c = 0;
// or, consume the preceding '('.
else --c;
}
}
return ans + c * 2;
}
};