链接
第一种解法
class Solution {
public:
string removeOuterParentheses(string S) {
string res = "";
int count = 0;
for(char ch : S)
{
if(ch == '(' && count ++ >0)
{
res += ch;
}
if(ch == ')' && count-- > 1)
{
res += ch;
}
}
return res;
}
};
第二种解法
利用栈来实现,去除最外层括号,即当栈为空时,不获得当前符号,栈为非空时,获取当前符号。
class Solution {
public:
string removeOuterParentheses(string S) {
string res = "";
stack<char> mystack;
for(char ch : S) {
if (ch == ')')
mystack.pop();
if (!mystack.empty())
res+=ch;
if (ch == '(')
mystack.push('(');
}
return res;
}
};