[题解][LeetCode][Valid Parentheses]

来源:互联网 发布:淘宝严重违规12分2999 编辑:程序博客网 时间:2024/04/30 17:22

题目:

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.

题解:

【字符串处理】

用一个List当作堆栈,遇到左括号压栈,遇到右括号弹栈比较。

最后check一下栈是否为空即可。


Code:

class Solution:# @return a booleandef isValid(self, s):p = []l = ['(','[','{']r = [')',']','}']for c in s:if c in l:p.append(c)elif c in r:if p == []:return Falseif p.pop() != l[r.index(c)]:return Falseif p == []:return Trueelse:return False


0 0