Intuition¶
The string is a concatenation of primitive valid parentheses groups. Each
primitive group starts at depth 0, rises to depth 1 on its opening (, and
returns to depth 0 on its closing ). The outermost ( and ) of each primitive
piece are exactly the characters seen at depth 0 — skip those and keep everything
in between.
Approach: Depth Counter¶
- Track
count= current nesting depth. - On
'(': append only ifcount > 0(not the outermost open), then increment. - On
')': decrement first, then append only ifcount > 0(not the outermost close). - Return the built string.
Complexity¶
- Time complexity: $$O(n)$$, where
niss.length— one pass over the string. - Space complexity: $$O(n)$$ for the output string.
Code¶
Go¶
func removeOuterParentheses(s string) string {
count := 0
ans := make([]uint8, 0, len(s))
for _, ch := range s {
if ch == '(' {
if count > 0 {
ans = append(ans, '(')
}
count++
} else if ch == ')' {
count--
if count > 0 {
ans = append(ans, ')')
}
}
}
return string(ans)
}