LeetCode - 20. Valid Parentheses (Python)

조민수·2024년 6월 3일
0

LeetCode

목록 보기
9/64
post-custom-banner

Easy, 스택

RunTime : 37 ms / Memory : 16.41 MB


문제

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. Every close bracket has a corresponding open bracket of the same type.

풀이

  • 여러번 접해봤던 stack 문제
  • 풀 만 했다.
class Solution:
    def isValid(self, s: str) -> bool:
        stack = []

        brackets = {
                    '}' : '{',
                    ')' : '(',
                    ']' : '['
                    }

        for w in s:
            if w in brackets.values():      # 여는 괄호
                stack.append(w)
            else:
                if stack and brackets[w] == stack[-1]:
                    stack.pop()
                else:
                    return False
        
        if stack:
            return False
        return True
profile
사람을 좋아하는 Front-End 개발자
post-custom-banner

0개의 댓글