key question to solving this problem: how to identify if parentheses is outermost?? here we can see nested parentheses and seperate several nested parentheses. One feature of a parentheses is it always appear in pairs. So we may think of using counter to increment when encounting open parentheses and decrement when facing closing parentheses. ==> first time see ( , skip, last time see ), skip
class Solution:
def removeOuterParentheses(self, S: str) -> str:
# tc O(N) sc O(N)
n = len(S)
cnt = 0
res = []
for i in range(n):
if S[i] == '(':
if cnt > 0:
res.append('(')
cnt += 1
else:
if cnt >1:
res.append(')')
cnt -=1
return ''.join(res)