一.题目:
给定一个包含’(’, ‘)’, ‘{’, ‘}’, ‘[’ 和 ']'的字符串,判断它是否是有效的.
二.解题思路:
设计一个栈,遍历字符串,当字母是左括号时压入栈中,当是右括号是看此时栈顶元素是否是对应的左括号.
代码如下:
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for i in s:
if i=="(" or i=="[" or i=="{":
stack.append(i)
else:
if i==")":
if stack!=[] and stack[-1]=="(":
stack.pop()
continue
else:
return False
elif i=="]":
if stack!=[] and stack[-1]=="[":
stack.pop()
continue
else:
return False
else:
if stack!=[] and stack[-1]=="{":
stack.pop()
continue
else:
return False
return stack == []