Leetcode Day5 (单调栈)

单调栈:通常是一维数组,要寻找任一个元素的右边或者左边第一个比自己大或者小的元素的位置,此时我们就要想到可以用单调栈了

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值