解法:栈
建立一个字符顺序栈stack,用i遍历stack,当遇到各种类型的左括号时进栈,
当遇到右括号时,若栈空或栈顶元素不是匹配的左括号时返回False(中间就可
以确定括号不匹配),否则退栈一次继续判断
当stack遍历完毕,栈空(全部匹配,且全部退栈)则返回True,否则False
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for i in range(len(s)):
e = s[i]
if e == '(' or e == '[' or e =='{':
stack.append(e)
else:
if e == ')':
if len(stack) == 0 or stack[len(stack)-1] != '(':
return False
stack.pop()
if e == '}':
if len(stack) == 0 or stack[len(stack)-1] != '{':
return False
stack.pop()
if e == ']':
if len(stack) == 0 or stack[len(stack)-1] != '[':
return False
stack.pop()
if len(stack) == 0:
return True
else:
return False
a = Solution()
s = "()"
print(a.isValid(s))