Remove Outermost Parentheses

easy stack string depth counter

Problem

A valid parentheses string is either empty, "(" + A + ")" where A is valid, or A + B where A and B are valid. A valid string s can be split into primitive pieces. Remove the outermost parentheses of every primitive piece of s and return the resulting string.

Inputs = "(()())(())"
Output"()()()"
The primitives are "(()())" and "(())". Stripping their outer pair gives "()()" and "()", concatenated to "()()()".

def remove_outer_parentheses(s):
    res = []
    depth = 0
    for c in s:
        if c == '(':
            if depth > 0:
                res.append(c)
            depth += 1
        else:
            depth -= 1
            if depth > 0:
                res.append(c)
    return ''.join(res)
function removeOuterParentheses(s) {
  let res = "";
  let depth = 0;
  for (const c of s) {
    if (c === '(') {
      if (depth > 0) res += c;
      depth++;
    } else {
      depth--;
      if (depth > 0) res += c;
    }
  }
  return res;
}
class Solution {
    public String removeOuterParentheses(String s) {
        StringBuilder res = new StringBuilder();
        int depth = 0;
        for (char c : s.toCharArray()) {
            if (c == '(') {
                if (depth > 0) res.append(c);
                depth++;
            } else {
                depth--;
                if (depth > 0) res.append(c);
            }
        }
        return res.toString();
    }
}
string removeOuterParentheses(string s) {
    string res;
    int depth = 0;
    for (char c : s) {
        if (c == '(') {
            if (depth > 0) res += c;
            depth++;
        } else {
            depth--;
            if (depth > 0) res += c;
        }
    }
    return res;
}
Time: O(n) Space: O(n)