ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 20. Valid Parentheses
    Leetcode 2021. 5. 10. 15:54

    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

    Example 4:

    Input: s = "([)]" Output: false

    Example 5:

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

     

    Constraints:

    • 1 <= s.length <= 104
    • s consists of parentheses only '()[]{}'.
    class Solution(object):
        def isValid(self, s):
            """
            :type s: str
            :rtype: bool
            """
            left = ["(", "{", "["]
            brackets = ["()", "{}", "[]"]
            stack = []
            
            
            for c in s:
                if len(stack) == 0 or c in left:
                    stack.append(c)
                elif stack[-1] + c in brackets:
                    stack.pop()
                else:
                    return False
            
            if len(stack) == 0:
                return True
            else:
                return False
            

    - 스택을 활용하면 쉽게 풀 수 있는 문제

    'Leetcode' 카테고리의 다른 글

    22. Generate Parentheses  (0) 2021.05.18
    21. Merge Two Sorted Lists  (0) 2021.05.11
    19. Remove Nth Node From End of List  (0) 2021.05.10
    18. 4Sum  (0) 2021.05.10
    17. Letter Combinations of a Phone Number  (0) 2021.05.10
Designed by Tistory.