有效括号字符串为空 ("")、"(" + A + “)” 或 A + B,其中 A 和 B 都是有效的括号字符串,+ 代表字符串的连接。例如,"","()","(())()" 和 “(()(()))” 都是有效的括号字符串。
如果有效字符串 S 非空,且不存在将其拆分为 S = A+B 的方法,我们称其为原语(primitive),其中 A 和 B 都是非空有效括号字符串。
给出一个非空有效字符串 S,考虑将其进行原语化分解,使得:S = P_1 + P_2 + … + P_k,其中 P_i 是有效括号字符串原语。
对 S 进行原语化分解,删除分解中每个原语字符串的最外层括号,返回 S 。
计数:
class Solution {
public:
string removeOuterParentheses(string S) {
string result; // 存储结果
int left = 0; //记录左括号的个数
int right = 0; //记录右括号的个数
for(int i=0; i<S.size(); i++){
if(S[i] == '(')
left++;
else if(S[i] == ')')
right++;
if(left == right){
//退回到需要加入的位置
for(int j = i-(left-1)*2; j<i; j++)
result.push_back(S[j]);
left = 0;
right = 0;
}
}
return result;
}
};
使用栈:
class Solution {
public:
string removeOuterParentheses(string S) {
string res = "";
stack<char> stack1;
for (int i = 0; i < S.size(); i++) {
if (S[i] == ')')
stack1.pop();
if (!stack1.empty())
res+=S[i];
if (S[i] == '(')
stack1.push('(');
}
return res;
}
};