코드

Valid Parentheses

ehei 2020. 2. 12. 23:56

https://leetcode.com/problems/valid-parentheses/

괄호가 잘 닫혔는지 검사하는 문제

 

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        pairs = {
            ')' : '(',
            ']' : '[',
            '}' : '{',
        }
        
        for ch in s:
            if ch in ( '(', '[', '{' ):
                stack.insert( 0, ch )
            else:
                if not stack:
                    return False
                else:
                    openBracket = stack.pop( 0 )
                    
                    if pairs[ ch ] != openBracket:
                        return False
                    
        return not stack