20. Valid Parentheses

时间:2022-02-28 13:23:06

1.题目:

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

这个题目不难理解,就是我们平时写程序时候,小括号,中括号,大括号都要对应的包起来,否则就有问题。

现在给定一个字符串,需要你来判断一下这个字符串是否满足该要求!

2.代码:

该问题,用栈的后进先出结构就很容易解决了。分三种情况,1. 下一个元素是左边的,直接入栈;2.下一个元素是右边的,要看能否和栈顶元素匹配,不匹配当然有问题了;3.匹配的话,刚好抵消掉栈顶元素,栈顶元素出栈;最后,判断下栈有没有完全抵消即可。

# -*-coding:utf-8-*-
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
left = ['(','[','{']
right = [')',']','}']
l = list(s)
stack = []
left_count,right_count = 0,0
#从左到右遍历字符串
while len(l)>0:
#如果这个字符是在left中,就写进stack
if l[0] in left:
stack.append(l[0])
#如果这个字符在right中,先判断stack,如果stack为空,直接返回False,如果stack的最后一位和该字符不匹配(否则会出现交叉情况,例如([)]),也直接返回False
#如果stack的最后一位和该字符刚好匹配,则从stack中弹出匹配到的字符
elif l[0] in right:
if len(stack)==0:return False
#print (l[0],' ',stack[-1])
#print (right.index(')'))
if right.index(l[0])==left.index(stack[-1]):
stack.pop()
else:
return False
#如果输入不是这些,也返回False,题目中说了 just the characters,只有这六个字符
else:
return False
l.remove(l[0])
#最后判断stack是否刚好抵消
return len(stack)==0 if __name__=='__main__':
s = '(('
a = Solution()
print (a.isValid(s))