2020-05-12
1,题目描述
使括号有效的最少添加
2.题解
进行括号匹配之后看栈里还剩下几个元素即可。
3.代码
class Solution {
public:
int minAddToMakeValid(string S) {
int l=S.length();
stack<char> mystack;
for (int i=0;i<l;i++){
if (S[i]=='(') mystack.push(S[i]);
else{
if (!mystack.empty()){
if (mystack.top()=='(') mystack.pop();
else mystack.push(S[i]);
}else{
mystack.push(S[i]);
}
}
}
int cnt=0;
while (!mystack.empty()){
cnt++;
mystack.pop();
}
return cnt;
}
};