首页 > 其他分享 >LeetCode Top Interview 150 - Stack

LeetCode Top Interview 150 - Stack

时间:2025-01-13 20:31:36浏览次数:3  
标签:150 Top sign pop self num Interview stk stack

Some scenarios where a stack is typically the appropriate data structure to use:

1. Parentheses Matching: Problems that require checking for balanced parentheses or brackets often utilize stacks to ensure that every opening bracket has a corresponding closing bracket.

2. Depth-First Search (DFS): When traversing trees or graphs, a stack can be used to implement DFS iteratively, allowing you to explore nodes in a last-in, first-out manner.

3. Backtracking: In problems that require exploring all possible configurations (like permutations or combinations), stacks can help manage the state as you backtrack through different paths.

4. Next Greater Element: Problems that require finding the next greater element for each element in an array can often be solved efficiently using a stack to keep track of indices.

5. Sorting: Some sorting problems, such as sorting a stack itself, can be approached using additional stacks to hold elements temporarily.

6. Expression Evaluation: Evaluating postfix or infix expressions can be effectively handled using stacks to manage operators and operands.

7. Sliding Window Problems: In certain sliding window problems, stacks can help maintain the order of elements and efficiently compute results based on the current window.

8. History Tracking: Problems that require tracking previous states or actions (like undo functionality) can utilize stacks to store and retrieve states in a manageable way.

In summary, whenever you encounter problems that involve nested structures, require backtracking, or need to maintain a specific order of operations, consider using a stack as your primary data structure.


For the remaining types of problems, please refer to my channel. 

everecursion-CSDN博客everecursion关注python,github,chatgpt领域.https://blog.csdn.net/gcsyymm?type=blog


Valid Parentheses

Valid Parenthesesicon-default.png?t=O83Ahttps://leetcode.cn/problems/valid-parentheses/Difficulty:EZ

class Solution:
    def isValid(self, s: str) -> bool:
        pairs = {
            "}": "{",
            "]": "[",
            ")": "(",
        }
        stk = []
        for c in s:
            # if it is a left half; get inside stk
            if c not in pairs:
                stk.append(c)
            else:
                # it is a right half; stk is empty or mismatch
                if not stk or pairs[c] != stk[-1]:
                    return False
                stk.pop()
        return not stk

Simplify Path 

Simplify Pathicon-default.png?t=O83Ahttps://leetcode.cn/problems/simplify-path/Difficulty:MED

class Solution:
    def simplifyPath(self, path: str) -> str:
        stk = []
        for p in path.split("/"):
            # omit all empty and .
            if p == "." or not p:
                continue
            # it is not a ..; it is a valid dir
            elif p != "..":
                stk.append(p)
            # if there are parent dir; pop it
            elif stk:
                stk.pop()
        return "/" + "/".join(stk)

Min Stack

Min Stackicon-default.png?t=O83Ahttps://leetcode.cn/problems/min-stack/Difficulty:MED

class MinStack:

    def __init__(self):
        # create the dummy item for comparison, first is val, second is min seen
        self.stk = [("dummy", inf)]

    def push(self, val: int) -> None:
        self.stk.append((val, min(val, self.stk[-1][1])))

    def pop(self) -> None:
        self.stk.pop()

    def top(self) -> int:
        return self.stk[-1][0]

    def getMin(self) -> int:
        return self.stk[-1][1]


# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()

Evaluate Reverse Polish Notation

Evaluate Reverse Polish Notationicon-default.png?t=O83Ahttps://leetcode.cn/problems/evaluate-reverse-polish-notation/Difficulty:MED

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        for token in tokens:
            # the negative number cant found with isdigit as there is a minus sign
            # thus check the last chr of the token
            if token[-1].isdigit():
                stack.append(int(token))
            else:
                operand1 = stack.pop()
                operand2 = stack.pop()
                if token == "+":
                    stack.append(operand1 + operand2)
                elif token == "-":
                    stack.append(operand2 - operand1)
                elif token == "*":
                    stack.append(operand1 * operand2)
                elif token == "/":
                    stack.append(
                        operand2 // operand1
                        if operand1 * operand2 > 0
                        else -(abs(operand2) // abs(operand1))
                    )
        return stack.pop()

Basic Calculator 

Basic Calculatoricon-default.png?t=O83Ahttps://leetcode.cn/problems/basic-calculator/Difficulty:HARD(NOT THAT HARD)

class Solution:
    def calculate(self, s: str) -> int:
        # num record concatenate digits;
        # res record current result;
        # sign record current positivity;
        # stk handle the parentheses
        num, res, sign, stk = "", 0, 1, []
        for c in s:
            # record the concatenate digits until see other chr
            if c.isdigit():
                num += c
            # update current result
            elif c in "+-":
                res += int(num) * sign if num else 0
                # reset the num
                num = ""
                # update positivity
                sign = 1 if c == "+" else -1
            elif c == "(":
                # record the result first
                stk.append(res)
                # then record the sign come before the parentheses
                stk.append(sign)
                # reset the result and positivity inside
                res, sign = 0, 1
            elif c == ")":
                # update the result
                res += int(num) * sign if num else 0
                # reset the num and positivity
                num = 0
                sign = 1
                # concatenate the result inside () with previous result
                res *= stk.pop()
                res += stk.pop()
        # handle end
        if num:
            res += int(num) * sign
        return res

For the remaining types of problems, please refer to my channel. 

everecursion-CSDN博客everecursion关注python,github,chatgpt领域.https://blog.csdn.net/gcsyymm?type=blog

标签:150,Top,sign,pop,self,num,Interview,stk,stack
From: https://blog.csdn.net/gcsyymm/article/details/145122302

相关文章

  • 【docker】docker desktop换国内源时 apply按钮为灰色or换源失败 解决方法
    配docker环境时复制进去国内镜像源后,发现apply按钮为灰色,点不了,如下图解决方法:往下滑,找到下图圈住的选项打勾再回到DockerEngine界面,发现可以点apply按钮了在文本框中添加"registry-mirrors":["http://mirrors.ustc.edu.cn", "http://mirror.azure.cn"]......
  • springboot短视频推荐系统-计算机设计毕业源码21503
    基于协同过滤算法的短视频推荐系统摘 要本论文基于协同过滤算法,旨在设计并实现一种基于SpringBoot框架的短视频推荐系统。该系统主要分为平台用户和管理员两类角色,用户可以注册、登录、浏览短视频内容,并根据个人兴趣收藏喜爱的视频。管理员则可以管理系统数据、用户和内容......
  • springboot短视频推荐系统-计算机设计毕业源码21503
    基于协同过滤算法的短视频推荐系统摘 要本论文基于协同过滤算法,旨在设计并实现一种基于SpringBoot框架的短视频推荐系统。该系统主要分为平台用户和管理员两类角色,用户可以注册、登录、浏览短视频内容,并根据个人兴趣收藏喜爱的视频。管理员则可以管理系统数据、用户和内容......
  • 使用 Podman Desktop 在 Windows 11 WSL2 环境中启动宿主机的 GPU 进行深度学习
    使用PodmanDesktop在Windows11WSL2环境中启动宿主机的GPU进行深度学习概述本文将指导您如何利用PodmanDesktop安装时提供的WSL2环境,来启动宿主机的GPU进行深度学习任务。前提条件确保您的Windows11已经启用了WSL2和虚拟化功能,并且安装了最新版本的NVIDI......
  • wx.stopCompass
    wx.stopCompass(Objectobject)基础库1.1.0开始支持,低版本需做兼容处理。以Promise风格调用:支持小程序插件:支持,需要小程序基础库版本不低于1.9.6功能描述停止监听罗盘数据参数Objectobject属性类型默认值必填说明successfunction否接口调用成......
  • wx.stopDeviceMotionListening
    wx.stopDeviceMotionListening(Objectobject)基础库2.3.0开始支持,低版本需做兼容处理。以Promise风格调用:支持小程序插件:支持,需要小程序基础库版本不低于2.9.1功能描述停止监听设备方向的变化。参数Objectobject属性类型默认值必填说明successfu......
  • wx.stopGyroscope
    wx.stopGyroscope(Objectobject)基础库2.3.0开始支持,低版本需做兼容处理。以Promise风格调用:支持小程序插件:支持,需要小程序基础库版本不低于2.9.1功能描述停止监听陀螺仪数据。参数Objectobject属性类型默认值必填说明successfunction否接口......
  • c语言 getopt的概念和使用方法
    在C语言中,getopt函数是一个用于解析命令行参数的库函数,它定义在<unistd.h>头文件中。getopt函数允许程序处理短格式的命令行选项(例如-a),并且可以处理选项参数。概念getopt函数的主要目的是解析命令行参数中的选项,它按照以下规则工作:选项必须以短横线-开头。选项......
  • LeetCode Top Interview 150 - Matrix
    ThisismerelymypersonalreviewofallthetypicalproblemsthatconstitutethemindsetforDataStructuresandAlgorithms(DSA).pythonsolutionprovidedFortheremainingtypesofproblems,pleaserefertomychannel.everecursion-CSDN博客everecursion......
  • 施耐德 三菱 西门子PLC 以太网口S7-1200/1500系列通讯协议解析说明文档
       资料参考链接:https://item.taobao.com/item.htm?abbucket=1&id=766532329733&ns=1&pisk=g0VseN0PDhxsC5j0KlbEVm4PVjhjhw5yfEgYrrdwkfhtDJaucc7cIfyIckEIXC7GIxnbjfH0QmoZcja0VwSPa_zgSjcR4g5yCEod7bAxWqKqv23rGVC1T97TSjcA4eRAU_ag2s7Opd3xJwgqlFnYDAhpvVoKWd......