1021. Remove Outermost Parentheses
LeetCode Daily Problem: Remove Outermost Parentheses
On this page
A valid parentheses string is either empty "", "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation.
- For example,
"","()","(())()", and"(()(()))"are all valid parentheses strings.
A valid parentheses string s is primitive if it is nonempty, and there does not exist a way to split it into s = A + B, with A and B nonempty valid parentheses strings.
Given a valid parentheses string s, consider its primitive decomposition: s = P1 + P2 + ... + Pk, where Pi are primitive valid parentheses strings.
Return s after removing the outermost parentheses of every primitive string in the primitive decomposition of s.
Constraints:
1 <= s.length <= 10^5s[i]is either'('or')'.sis a valid parentheses string.
Approach: Straight simulation
The task is clear: remove every parenthesis at depth 0. One pass is enough.
The official solution gives two equivalent methods. The stack version uses whether the stack is empty to tell whether the current depth is 0.
Why process ) before checking the depth and ( after? Because an opening bracket's real depth is the depth before entering it, while a closing bracket's real depth is the depth after leaving it.
class Solution:
def removeOuterParentheses(self, s: str) -> str:
dph = 0
ans = ''
for c in s:
if c == ')':
dph -= 1
if dph > 0:
ans += c
if c == '(':
dph += 1
return ansComplexity
- Time: O(n) — one pass over the string.
- Space: O(1) extra space, excluding the output.