LeetCode 20. Valid Parentheses

개발공부를해보자·2025년 1월 13일

LeetCode

목록 보기
20/95

파이썬 알고리즘 인터뷰 문제 20번(리트코드 20번) Valid Parentheses
https://leetcode.com/problems/valid-parentheses/

나의 풀이

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

        for char in s:
            if char in close_brackets:
                if not stack or stack.pop() != close_brackets[char]: # empty stack case
                    return False
            else:
                stack.append(char)

        return not stack

오답, 배운 점

  • 처음부터 닫힌 괄호가 나와서 stack 비어 있는 경우를 생각하지 못하여 not stack 조건을 누락했었다.
  • Stack을 이용할 때는 비어있는 경우를 빠트리지 말자.
profile
개발 공부하는 30대 비전공자 직장인

0개의 댓글