1021. 删除最外层的括号
解法一:栈
维护一个栈,遍历字符串,遇到 (
和 )
要进行入栈和出栈操作,还要吧字符串放进结果中。
下面两种情况不放进结果,这代表最外层的:
1、s[i] === '(' && stack.length === 0
2、s[i] === ')' && stack.length === 1
/**
* @param {string} s
* @return {string}
*/
var removeOuterParentheses = function (s) {
const stack = [];
let res = "";
for (let i = 0; i < s.length; i++) {
if (s[i] === "(" && !stack.length) {
stack.push("(");
} else if (s[i] === "(" && stack.length) {
stack.push("(");
res += s[i];
} else if (s[i] === ")" && stack.length === 1) {
stack.pop();
} else if (s[i] === ")") {
stack.pop();
res += s[i];
} else {
res += s[i];
}
}
return res;
};