본문 바로가기

Programming/알고리즘 파이썬 문제풀이

[Python/LeetCode] 20. Valid Parentheses

입력 :

괄호로 된 입력값이 올바른지 판별하는 문제.

"()[]{}" 와 같은 입력이 주어졌을 때, 이 수식에 모순이 있으면 FALSE, 아니면 TRUE를 반환하면 됨.

 

풀이 :

dictionary로 정의된 table과 stack을 사용. 

expression 관련 문제는 stack을 사용하면 좋다.

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        table = {
            ')': '(',
            '}': '{',
            ']': '[',
        }

        # 스택 이용 예외 처리 및 일치 여부 판별
        for char in s:
            if char not in table:
                stack.append(char)
            elif not stack or table[char] != stack.pop():
                return False
        return len(stack) == 0