20. Valid Parentheses

meta fring·2023년 7월 27일
0

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

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

An input string is valid if:

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

Example 1:

Input: s = "()"
Output: true
Example 2:

Input: s = "()[]{}"
Output: true
Example 3:

Input: s = "(]"
Output: false
 

Constraints:

1 <= s.length <= 104
s consists of parentheses only '()[]{}'.

괄호가 알맞게 잘 닫혔는지 검사하면 된다.

class Solution:
    def isValid(self, s: str) -> bool:
        open = ["(", "{", "["]
        basket = []

        for a in s:
            if a in open:
                basket.append(a)
            else:
                if a == ")":
                    if not basket or basket.pop() != "(":
                        return False
                elif a == "}":
                    if not basket or basket.pop() != "{":
                        return False
                elif a == "]":
                    if not basket or basket.pop() != "[":
                        return False
        if len(basket) > 0:
            return False
        return True

여는 괄호인지 검사해서 맞다면 basket에 넣어준다.
그리고 닫는 괄호이면 basket 마지막 값과 매칭되는지 검사한다.
마지막으로 basket에 값이 남아있다면, 즉 닫는 괄호가 없이 그대로 열린 괄호가 남아있는지 검사한다.
걸리는 게 없다면 True 리턴.

profile
긍정적인 개발자

0개의 댓글