leetcode20 python valid parentheses

Given a string containing only  '(', ')', '{', '}', '[', ']' check whether the string is valid.

A valid string must satisfy:

  1. Opening parentheses must be closed with closing parentheses of the same type.
  2. Left parentheses must be closed in the correct order.

Note that empty strings are considered valid strings.

Example 1:

Input: "()"
 Output: true

Example 2:

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

Example 3:

Input: "(]"
 Output: false

Example 4:

Input: "([)]"
 Output: false

Example 5:

Input: "{[]}"
 Output: true
python code

class Solution:
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        dic={'(':')','[':']','{':'}'}
        stack=[]#Use the data structure of stack
        for current in s:
            if current in dic.keys():
                stack.append(current)
            elif current in dic.values():
                if len(stack) == 0 or dic.get(stack[-1]) != current:# Corresponding to the two cases such as []}, [} respectively
                    return False
                else:
                    stack.pop()
        if len(stack)==0:
            return True
        else:
            return False
                

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325801055&siteId=291194637