I am working on question 1249. Minimum Remove to Make Valid Parentheses on LeetCode. It is an easy question which I can solve with stack in both C++ and Python. However, my C++ version code leads to Memory Limit Exceeded, while my exact same Python code only consumes 15.3 MB memory. Could anyone help me understand what is wrong, please?
C++ code:
class Solution {
public:
string minRemoveToMakeValid(string s) {
stack<pair<char, int>> stack;
for (int i=0; i<s.size();i++){
if (s[i]!='(' && s[i]!=')')
continue;
else{
if (!(stack.empty()) && stack.top().first=='(' && s[i]==')')
stack.pop();
else
stack.push({s[i],i});
}
}
string res;
for (int i=s.size()-1; i>=0;i--){
if (!stack.empty() && i==stack.top().second)
stack.pop();
else{
res = s[i] + res;
}
}
return res;
}
};
Even if replace stack data structure in C++ with vector, it still leads to Memory Limit Exceeded.
Python3
class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack = []
for i, c in enumerate(s):
if c!="(" and c!=")":
continue
if stack and stack[-1][0] == '(' and c==")":
stack.pop()
else:
stack.append([c,i])
res =""
for i in range(len(s)-1,-1,-1):
if stack and i == stack[-1][1]:
stack.pop()
else:
res = s[i] + res
return res