Using stack to solve the Parentheses problems

Jimmy (xiaoke) Shen
1 min readAug 8, 2020

This week’s biweekly contest, we have a Parentheses problem. For this kind of problem, usually, we can solve it by using a stack. Here is the problem and solution.

Problem

1541. Minimum Insertions to Balance a Parentheses String

Code

class Solution {
public:
int minInsertions(string s) {
stack<char> stack;
int ret = 0;
for (auto c : s)
{
if (stack.empty())
{
stack.push(c);continue;
}
if (c==')' && stack.top() == ')')
{
stack.pop();
//case of "))"
if(stack.empty())
{
ret += 1;
continue;
}
// case of "())"
else
{
stack.pop();
}
}
else if (c==')' && stack.top() == '(')
{
stack.push(c);
}
else if (c=='(' && stack.top() == '(')
{
stack.push(c);
}
else if (c=='(' && stack.top() == ')')
{
stack.pop();
if(stack.empty())
{
ret += 2;
stack.push(c);
continue;
}
else
{
stack.pop();
ret += 1;
stack.push(c);
continue;
}
}
}
if(!stack.empty() && stack.top()==')')
{

stack.pop();
//case of ")"
if(stack.empty())ret += 2;
//case of "()"
else
{
ret += 1;
//stack.pop();
stack.pop();
}

}
ret += 2*stack.size();
return ret;
}
};

32. Longest Valid Parentheses

See[1]

Reference

[1]https://youtu.be/677VaZhd4dg

--

--