单调栈:通常是一维数组,要寻找任一个元素的右边或者左边第一个比自己大或者小的元素的位置,此时我们就要想到可以用单调栈了
739 每日温度
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
stack = []
res = [0] * len(temperatures)
for i in range(len(temperatures)):
num = temperatures[i]
if len(stack) == 0:
stack.append(i)
if num <= temperatures[stack[-1]]:
stack.append(i)
while len(stack) > 0 and num > temperatures[stack[-1]] :
index = stack.pop()
res[index] = i - index
stack.append(i)
return res
这是我第一次直接写出来的
class Solution:
def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
stack = []
res = [0] * len(temperatures)
for i in range(len(temperatures)):
num = temperatures[i]
if len(stack) == 0:
stack.append(i)
if num <= temperatures[stack[-1]]:
stack.append(i)
while len(stack) > 0 and num > temperatures[stack[-1]]:
index = stack.pop()
res[index] = i - index
stack.append(i)
return res
简化版本好看多了
150 逆波兰表达式
输入:tokens = [“4”,“13”,“5”,“/”,“+”]
输出:6
解释:该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6
394 解码
class Solution:
def decodeString(self, s: str) -> str:
stack = []
for c in s:
if c != "]":
stack.append(c)
else:
# sub string
sub_string = ""
while stack and stack[-1].isalpha():
sub_string = stack.pop() + sub_string
stack.pop() # 去除'['
# sub multiplier
sub_multiplier = ''
while stack and stack[-1].isdigit():
sub_multiplier = stack.pop() + sub_multiplier
sub_multiplier = int(sub_multiplier)
partial = sub_string * sub_multiplier
stack.append(partial)
return ''.join(stack)