1021.删除最外层的括号
链接:1021.删除最外层的括号
难度:Easy
标签:栈、字符串
简介:对 S 进行原语化分解,删除分解中每个原语字符串的最外层括号,返回 S 。
题解 1 - typescript
- 编辑时间:2021-03-19
- 执行用时:96ms
- 内存消耗:39.7MB
- 编程语言:typescript
- 解法介绍:利用栈维护内层括号。
function removeOuterParentheses(S: string): string {
  const stack: string[] = [];
  let ans = '';
  let deep = 0;
  let count = 0;
  for (const c of S) {
    if (c === '(') {
      stack.push(c);
      deep++;
      count++;
    } else if (--deep === 0) {
      let str = '';
      while (--count !== 0) str = stack.pop()! + str;
      ans += str;
    } else {
      stack.push(c);
      count++;
    }
  }
  return ans;
}
题解 2 - cpp
- 编辑时间:2022-05-28
- 内存消耗:6.4MB
- 编程语言:cpp
- 解法介绍:一次遍历, 储存当前等级。
class Solution {
   public:
    string removeOuterParentheses(string s) {
        string ans = "";
        int level = 0;
        for (auto& ch : s) {
            if (ch == '(') {
                if (level != 0) ans += ch;
                level++;
            } else {
                level--;
                if (level != 0) ans += ch;
            }
        }
        return ans;
    }
};