Skip to content

1021. Remove Outermost Parentheses

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  string removeOuterParentheses(string s) {
    string ans;
    int opened = 0;

    for (const char c : s)
      if (c == '(') {
        if (++opened > 1)
          ans += c;
      } else if (--opened > 0) {  // c == ')'
        ans += c;
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public String removeOuterParentheses(String s) {
    StringBuilder sb = new StringBuilder();
    int opened = 0;

    for (final char c : s.toCharArray())
      if (c == '(') {
        if (++opened > 1)
          sb.append(c);
      } else if (--opened > 0) { // c == ')'
        sb.append(c);
      }

    return sb.toString();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def removeOuterParentheses(self, s: str) -> str:
    ans = []
    opened = 0

    for c in s:
      if c == '(':
        opened += 1
        if opened > 1:
          ans.append(c)
      else:  # c == ')'
        opened -= 1
        if opened > 0:
          ans.append(c)

    return ''.join(ans)