Minimum Insertions to Balance a Parentheses String Solutions in C++Number 1541Difficulty MediumAcceptance 39.5%Link LeetCodeOther languages —SolutionsC++ solution by haoel/leetcode// Source : https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/// Author : Hao Chen// Date : 2020-10-02 class Solution {public: int minInsertions(string s) { vector<char> stack; int cnt = 0; int len = s.size(); for (int i=0; i<len; i++) { if ( s[i] == '(' ) { stack.push_back( s[i] ); continue; } // if s[i] is ')' if (stack.size() > 0) { stack.pop_back(); } else { cnt++; // missed the '(' } // if s[i+1] is ')', need to skip if ( i < len -1 && s[i+1] == ')' ) { i++; }else{ cnt++; //missed the ')' } } // if the stack still has '(', which means need double of ')' return cnt + stack.size()*2; }};// Source : https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/ // Author : Hao Chen // Date : 2020-10-02 class Solution { public: int minInsertions(string s) { vector<char> stack; int cnt = 0; int len = s.size(); for (int i=0; i<len; i++) { if ( s[i] == '(' ) { stack.push_back( s[i] ); continue; } // if s[i] is ')' if (stack.size() > 0) { stack.pop_back(); } else { cnt++; // missed the '(' } // if s[i+1] is ')', need to skip if ( i < len -1 && s[i+1] == ')' ) { i++; }else{ cnt++; //missed the ')' } } // if the stack still has '(', which means need double of ')' return cnt + stack.size()*2; } };