方法一:
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if (len(s) % 2 == 1):
return False
dict_s = {"{":"}", "[":"]", "(":")"}
stack = []
for i in s: #s中的每一个括号
if i in dict_s: #如果i在dict_s中,就是判断左括号在其中
stack.append(i) #将其放在堆栈中
else: #如果不在dict_s中,一是不合法和括号,二是右括号
if not stack or dict_s[stack.pop()] != i: #如果第一个元素就不存在或者顺序不对
return False
return stack == []
方法二:
def isValid(s):
"""
:type s: str
:rtype: bool
"""
if (len(s) % 2 == 1):
return False
d = {')':'(', ']':'[', '}':'{'}
stack =[]
for i in s:
if i in d and d[i] == stack[-1]:
stack.pop()
else:
stack.append(i)
return stack == []