본문 바로가기
Leetcode

1021. Remove Outermost Parentheses

by YGSEO 2020. 6. 30.
728x90

STACK

 

말그대로 outermost parentheses를 제거하고 남은 string을 출력하는 문제

 

cnt 변수를 활용해서 list에 append하는 조건을 만들어서 해결

 

class Solution:
    def removeOuterParentheses(self, S: str) -> str:
        res = []
        check = 0
        for s in S:
            if s == "(" :
                check += 1
                if check > 1 :  # checking if it starts new paren or already added to "res" list
                    res.append(s)
                
            
            if s == ")":
                check -= 1
                if check >= 1:
                    res.append(s)
                
        return "".join(res)
        

잘 안될때는 노트에 table 만들어서

in check result
"(" 1(+1) []
"(" 2(+1) [ "(" ]
")" 1(-1) [ "(" , ")" ]
")" 0(-1) [ "(" , ")" ]

이런식으로 cnt를 활용해서 stack

 

 

728x90

'Leetcode' 카테고리의 다른 글

844. Backspace String Compare  (0) 2020.07.21
682. Baseball Game  (0) 2020.07.19
496. Next Greater Element I  (0) 2020.07.06
1047. Remove All Adjacent Duplicates In String  (0) 2020.07.05
1441. Build an Array With Stack Operations  (0) 2020.07.01

댓글