Given a string containing only '('
, ')'
, '{'
, '}'
, '['
, ']'
check whether the string is valid.
A valid string must satisfy:
- Opening parentheses must be closed with closing parentheses of the same type.
- 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