20. Valid Parentheses
題目:
https://leetcode.com/problems/valid-parentheses/
難度:
Easy
雖然知道肯定是用stack來(lái)解決,但是我是看了hint才自己解答的灸蟆,因?yàn)榭赡芟霃?fù)雜了亲族。
因?yàn)橐还仓挥腥N狀況"(" -> ")", "[" -> "]", "{" -> "}".
一遇到左括號(hào)就入棧吓歇,右括號(hào)出棧城看,這樣來(lái)尋找對(duì)應(yīng)
需要檢查幾件事:
- 右括號(hào)時(shí)stack里還有沒(méi)有東西
- 出stack的是否對(duì)應(yīng)
- 最終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 == []