본문 바로가기
Python/PS in Python

LeetCode 20. Valid Parentheses - Python

by Air’s Big Data 2020. 9. 21.

LeetCode 20. Valid Parentheses  - Python 

 

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

 

Solution: 

class Solution:
    def isValid(self, s: str) -> bool:          
        s_list = list(s)
        answer = True
        stack = [] 
        
        for s in s_list: 
            if s == '[' or s == '(' or s == '{':
                stack.append(s)
            elif len(stack) != 0:
                if (s == ']' and stack[-1] == '[') or (s == '}' and stack[-1] == '{') or (s == ')' and stack[-1] == '('):
                    stack.pop() 
                else: 
                    answer = False 
                    break 
            else: 
                answer = False 
                break 
        if len(stack) != 0:
            answer = False 
            
        return answer

댓글