20. Valid Parentheses
题目:
https://leetcode.com/problems/valid-parentheses/
难度:
Easy
虽然知道肯定是用stack来解决,但是我是看了hint才自己解答的,因为可能想复杂了。
因为一共只有三种状况"(" -> ")", "[" -> "]", "{" -> "}".
一遇到左括号就入栈,右括号出栈,这样来寻找对应
需要检查几件事:
- 右括号时stack里还有没有东西
- 出stack的是否对应
- 最终stack是否为空
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
leftP = "([{"
rightP = ")]}"
stack = []
for char in s:
if char in leftP:
stack.append(char)
elif char in rightP:
if stack == []:
return False
item = stack.pop()
if char == "]" and item != "[":
return False
elif char == ")" and item != "(":
return False
elif char == "}" and item != "{":
return False
return stack == []
网友评论