2020년/코테

[코테 연습] Valid Parentheses

위지원 2020. 9. 24. 22:33

leetcode.com/problems/valid-parentheses/

 

Valid Parentheses - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

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.

class Solution:
    def isValid(self, s: str) -> bool:
        #뚜껑과 그릇이 딱 만나는 순간에도 같아야한다
        stack = []
        
        for char in s:
            if char == "(" or char == "{" or char == "[":
                stack.append(char)
            if char == ")" : #testcase ")"때문에
                if not stack or stack[-1] != "(":
                    return False
                stack.pop()
            if char == "}" :
                if not stack or stack[-1] != "{":
                    return False
                stack.pop()
            if char == "]" :
                if not stack or stack[-1] != "[":
                    return False
                stack.pop()
        if stack: # testcase "["때문에
            return False
        return True