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) { int n = s.size(), c = 0, ans = 0; for (int i = 0; i < n; ++i) { if (s[i] == '(') { ++c; } else { if (i >= n - 1 || s[i + 1] != ')') ++ans; else ++i; if (c <= 0) ++ans, c = 0; else --c; } } return ans + c * 2; } };
|