有效括号问题
题目
20. Valid Parentheses解法
遇到左括号时push
,遇到右括号pop
。
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
dict = {"]":"[", "}":"{", ")":"("}
for char in s:
if char in dict.values():
stack.append(char)
elif char in dict.keys():
if stack == [] or dict[char] != stack.pop():
return False
else:
return False
return stack == []
等待时间问题
题目
739. Daily Temperatures解法
将天数指针存入堆栈中,当遇到更暖和的天气时,从堆栈中pop()。
def dailyTemperatures(self, T):
"""
:type T: List[int]
:rtype: List[int]
"""
ans = [0] * len(T)
stack = []
for i, t in enumerate(T):
while stack and T[stack[-1]] < t:
cur = stack.pop()
ans[cur] = i - cur
stack.append(i)
return ans
网友评论