Minimum Insertions to Balance a Parentheses String LeetCode solution in C++
1class Solution {2public:3int minInsertions(string s) {4stack<char> v;5int ans = 0;6for (int i = 0; i < s.size(); i++) {7if (s[i] == '(')8v.push(s[i]);9else {10if (s[i] == ')' && i < s.size() && s[i + 1] == ')') {11if (!v.empty())12v.pop();13else14ans++;15i++; // because we considered i+1 in this case16} else if (s[i] == ')' && i < s.size() && s[i + 1] != ')') {17if (!v.empty()) {18v.pop();19ans++;20} else21ans += 2;22}23}24}25if (v.empty()) return ans;26return v.size() * 2 + ans;27}28};