Python3解leetcode Valid Parentheses
问题描述:
Given a string 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.
Note that an empty string is also considered valid.
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
解题思路及方法:利用字典进行各个符号之间的配对;利用stack的先进后出特性进行验证
代码:
1 class Solution: 2 def isValid(self, s: str) -> bool: 3 if len(s)%2 != 0: return False 4 b = {'(':')', '[':']', '{':'}'} 5 stack = [] 6 for x in s: 7 if x in b: 8 stack.append(x) 9 else: 10 if stack and x==b[stack.pop()]: 11 continue 12 else : 13 return False 14 if stack: 15 return False 16 else: 17 return True 18