본문 바로가기

Algorithm

[LeetCode/Python] Valid Parentheses

문제 설명

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.

 

예시

 

제한

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

 

 

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

 

풀이

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        dict = {")":"(", "}":"{", "]":"["}
        for i in s:
            if i == "(" or i == "[" or i == "{":
                stack.append(i)
            elif i == ")" or i == "]" or i == "}":
                if len(stack) == 0:
                    return False
                if stack.pop() != dict[i]:
                    return False

        return len(stack) == 0

'Algorithm' 카테고리의 다른 글

[백준/Python] 설탕 배달  (0) 2021.10.03
[백준/Python] ATM  (0) 2021.09.28
[LeetCode/Python] Longest Common Prefix  (0) 2021.09.05
[LeetCode/Python] Roman to Integer  (0) 2021.09.05
[LeetCode/Python] Reverse Integer  (0) 2021.09.05