topic:
Includes only a given '(', ')' string, '{', '}', '[', ']', and determine whether the string is valid.
Valid string must meet:
Left bracket must be closed by a closing parenthesis of the same type.
Left parenthesis must be closed in the correct order.
Note the empty string can be considered a valid string.
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
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/valid-parentheses
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
answer:
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
# 1, stack
if len(s)%2!=0:
return False
dic = { '(', ')', '[', ']', '{', '}', '?', '?'}
stack = [ '?'] # when opening and closing brackets than in parentheses, stack.pop () reports an error, the process in advance
for c in s:
if c in dic:
stack.append (c) # push open parenthesis
elif dic [stack.pop ()] = c:! # close bracket, and paired comparison whether the closing parenthesis top of the stack
return False
return len(stack)==1
# 2, music Diminshing method timeout
if len(s)%2!=0:
return False
while len(s)>0 and ('()' in s or '{}' in s or '[]' in s ):
s.replace('()','')
s.replace('[]','')
s.replace('{}','')
return len(s)==0