[20] Valid Parentheses | Leetcode Easy

yoongyum·2022년 4월 7일
0

코딩테스트 🧩

목록 보기
7/47
post-thumbnail

문제설명

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.

결과예시

Example 1:

Input: s = "()"
Output: true

Example 2:

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

Example 3:

Input: s = "(]"
Output: false

제한사항

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

파이썬 코드

class Solution:
    def isValid(self, s: str) -> bool:
        arr = []
        if len(s) % 2 != 0 : return False #s의 길이가 짝수가 아니면 False반환.
        for c in s:
            if c == '(' or c == '{' or c == '[':
                arr.append(c)
            elif not self.fuc(arr, c):
                return False
                     
        return not arr      #배열이 비었으면 true 안비었으면 false
    
    def fuc(self, a ,c) -> bool:
        save = {')':'(' , '}':'{', ']':'['}
        if a and a[-1] == save[c]:
            a.pop()
            return True
        else : return False

0개의 댓글