[leetcode] 20. Valid Parentheses _ Algorithm Problem Solve for python



1. Problem

20. Valid Parentheses

Given a string s containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Every close bracket has a corresponding open bracket of the same type.

Example 1:

Input: s = "()"
Output: true

Example 2:

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

Example 3:

Input: s = "(]"
Output: false

Constraints:

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

2. Solution

I solve this problem like this.

  • Using stack and dictionary.
  • It loops through the for string and checks each word one by one.
  • If character is in ‘([{‘, push stack.
  • If character is not in ‘([{‘, check stack’s top value is pair of brackets.
class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        for _s in s:
            if _s in '([{':
                stack.append(_s)
                continue
            
            dic = {'(': ')', '[': ']', '{': '}'}

            if len(stack) > 0 and dic.get(stack[-1], None) == _s:
                stack.pop()
                continue
            else:
                return False

        return True if len(stack) == 0 else False