본문 바로가기
Algorithm/LEET CODE ( 파이썬 알고리즘 인터뷰)

[LEET CODE] 20. Valid Parentheses

by newnu 2021. 3. 23.
반응형

# Problem

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.

Constraints:

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

 

# My Answer

class Solution:
    def isValid(self, s: str) -> bool:
        pair = {
            ')':'(',
            ']':'[',
            '}':'{'
        }
        stack=[]
        for c in s:
            if c in pair.keys():
                if stack and stack.pop()==pair[c]:
                    continue
                else:
                    return False
            else:
                stack.append(c)
                
        if stack==[]:
            return True
        else:
            return False

 

# Solution 1

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
반응형