16.26. 计算器
参考方法:https://blog.csdn.net/Changxing_J/article/details/110313298
class Solution:
def calculate(self, s: str) -> int:
marks = {"+", "-", "*", "/"}
stack = [] # 多项式栈
now_num = "" # 当前数字
last_mark = "+" # 上一个符号
for ch in s + "+": # 在结尾添加无意义的运算符,使最后一个数字可以被计算
if ch.isdigit():
now_num += ch
elif ch in marks:
num = int(now_num) # 字符数字转为int
if last_mark == "+":
stack.append(num) # 如果遇到+先放入栈中
elif last_mark == "-":
stack.append(-num) # 如果遇到-,将负数加入栈中
elif last_mark == "*":
stack[-1] *= num #直接计算栈顶元素和当前数字的乘积等于栈顶元素
else:
stack[-1] = int(stack[-1] / num)
now_num = ""
last_mark = ch
return sum(stack)
739.每日温度
分析:
遍历数组,如果栈不空并且当前元素大于栈顶元素时,下标差就是二者的距离
否则,如果当前当前元素小于栈顶元素时,入栈。(从头到顶 生成一个递增的单调栈)
class Solution:
def dailyTemperatures(self, T: List[int]) -> List[int]:
stack = []
res = [0] * len(T)
i = 0
for i in range(len(T)):
while stack and T[i] > T[stack[-1]]:
res[stack[-1]] = i - stack[-1]
stack.pop()
stack.append(i)
return res