题目
代码(首刷自解)
这个题我的思路是先从左往右遍历,遇到字母和(
就放入res,并将(
放入栈,若遇到’)'则判断栈是否为空,若不为空则将)
放入res。最后遍历完后,再从右往左将多余的(
弹出,注意,必须是从右往左,如果从左往右会破坏掉已经搭建好的res。
class Solution {
public:
string minRemoveToMakeValid(string s) {
string res;
stack<char> stk;
for(char& c : s) {
if(c == '(') {
res += c;
stk.push(c);
} else if(c == ')') {
if(!stk.empty()) {
stk.pop();
res += c;
}
} else {
res += c;
}
}
int i = res.size() - 1;
while(!stk.empty()) {
if(res[i] == '(') {
res.erase(i, 1);
stk.pop();
} else {
i--;
}
}
return res;
}
};