• leetcode(2)栈


    leetcode 155 最小栈
    stack相当于栈,先进后出 存储全部栈元素 [-3,2,-1]
    min_stack,存储栈当前位置最小的元素 [-3,-3,-3]

    class MinStack:
        def __init__(self):
            self.stack = []
            self.min_stack = [math.inf]
    
        def push(self, x: int) :
            self.stack.append(x)
            self.min_stack.append(min(x, self.min_stack[-1]))
    
        def pop(self) -> None:
            self.stack.pop()
            self.min_stack.pop() #  也需要删除当前位置的最小元素
    
        def top(self) -> int:
            return self.stack[-1]
    
        def getMin(self) -> int:
            return self.min_stack[-1]
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    leetcode 20 有效括号

    class Solution:
        def isValid(self, s: str) -> bool:
            dic = {'{': '}',  '[': ']', '(': ')','?':'?'}
            stack = ["?"]
            for c in s:
                if c in dic: stack.append(c)
                elif dic[stack.pop()] != c: return False 
            return len(stack) == 1
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    leetcode 227 基本计算器2

    class Solution:
        def calculate(self, s: str) -> int:
            n = len(s)
            stack = []
            preSign = '+'
            num = 0
            for i in range(n):
                if s[i] != ' ' and s[i].isdigit():
                    num = num * 10 + ord(s[i]) - ord('0')
                if i == n - 1 or s[i] in '+-*/':
                    if preSign == '+':
                        stack.append(num)
                    elif preSign == '-':
                        stack.append(-num)
                    elif preSign == '*':
                        stack.append(stack.pop() * num)
                    else:
                        stack.append(int(stack.pop() / num))
                    preSign = s[i]
                    num = 0
            return sum(stack)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    leetcode 150 逆波兰表达式

    class Solution:
        def evalRPN(self, tokens: List[str]) -> int:
            op_to_binary_fn = {
                "+": add,
                "-": sub,
                "*": mul,
                "/": lambda x, y: int(x / y),   # 需要注意 python 中负数除法的表现与题目不一致
            }
    
            stack = list()
            for token in tokens:
                try:
                    num = int(token)
                except ValueError:
                    num2 = stack.pop()
                    num1 = stack.pop()
                    num = op_to_binary_fn[token](num1, num2)
                finally:
                    stack.append(num)
                
            return stack[0]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    leetcode 验证栈序列
    输入两个栈 A和B判断B是否为A的出栈序列
    输入:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
    输出:true
    解释:我们可以按以下顺序执行:
    push(1), push(2), push(3), push(4), pop() -> 4,
    push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

    class Solution:
        def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
            stack, i = [], 0
            for num in pushed:
                stack.append(num) # num 入栈
                while stack and stack[-1] == popped[i]: # 循环判断与出栈
                    stack.pop()
                    i += 1
            return not stack
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    leetcode 字符串编解码

    class Solution:
        def decodeString(self, s: str) -> str:
            stack, res, multi = [], "", 0
            for c in s:
                if c == '[':
                    stack.append([multi, res])
                    res, multi = "", 0
                elif c == ']':
                    cur_multi, last_res = stack.pop()
                    res = last_res + cur_multi * res
                elif '0' <= c <= '9':
                    multi = multi * 10 + int(c)            
                else:
                    res += c
            return res
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    leetcode 下一个更大元素

    class Solution1:
        def nextGreaterElement(self, nums1, nums2):
            dic = {}
            for i in range(len(nums2)):
                j = i + 1
                while j < len(nums2) and nums2[i] >= nums2[j]:
                    j += 1
                if j < len(nums2) and nums2[i] < nums2[j]:
                    dic[nums2[i]] = nums2[j]
            return [dic.get(x, -1) for x in nums1]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    leetcode 去除重复字符

    class Solution(object):
        def removeKdigits(self, num, k):
            stack = []
            remain = len(num) - k
            for digit in num:
                while k and stack and stack[-1] > digit:
                    stack.pop()
                    k -= 1
                stack.append(digit)
            return ''.join(stack[:remain]).lstrip('0') or '0'
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    leetcode 每日最高温度

    class Solution:
        def dailyTemperatures(self, temperatures):
            stack, ret = [], [0] * len(temperatures)
            for i, num in enumerate(temperatures):
                while stack and temperatures[stack[-1]] < num:
                    index = stack.pop()
                    ret[index] = i - index
                stack.append(i)
            return ret
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
  • 相关阅读:
    word 如何编写4x4矩阵
    在win10上安装pytorch-gpu版本2
    2023年中职“网络安全“—Web 渗透测试②
    Dubbo基本结构及执行流程
    大厂面试题:ReentrantLock 与 synchronized异同点对比
    【JavaEE】多线程案例-单例模式
    网络部分
    今年2023双十一腾讯云服务器的价格优惠力度如何?
    微服务12-分布式服务理论基础+Seata的认识
    GB/T 28627-2023 抹灰石膏检测
  • 原文地址:https://blog.csdn.net/weixin_43751285/article/details/133978609