Skip to content

1021. 删除最外层的括号

Posted on:2022年10月26日 at 14:18

1021. 删除最外层的括号

leetcode 链接

解法一:栈

维护一个栈,遍历字符串,遇到 () 要进行入栈和出栈操作,还要吧字符串放进结果中。

下面两种情况不放进结果,这代表最外层的:

1、s[i] === '(' && stack.length === 0

2、s[i] === ')' && stack.length === 1

/**
 * @param {string} s
 * @return {string}
 */
function removeOuterParentheses(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
}