【数据结构与算法】LeetCode:栈

news/2024/9/29 1:26:49/

文章目录

    • 用栈实现队列
    • 最小栈 (Hot 100)
    • 有效的括号 (Hot 100)
    • 字符串解码 (Hot 100)
    • 每日温度 (Hot 100)

用栈实现队列

用栈实现队列

class MyQueue {
private:stack<int> st_in;  // 输入栈,用于压入传入的数据stack<int> st_out; // 输出栈,st_out为st_in的倒序
public:MyQueue() {}void push(int x) {st_in.push(x);}int pop() {  if (st_out.empty()) {while (!st_in.empty()) {st_out.push(st_in.top()); st_in.pop();}}int out = st_out.top();st_out.pop();return out;}int peek() {int out = this->pop();st_out.push(out);return out;}bool empty() { return st_in.empty() && st_out.empty(); }
};

最小栈 (Hot 100)

最小栈

class MinStack {
private:stack<int>x_stack;stack<int>min_stack; // size与x_stack相同,存储当前最小值
public:MinStack() {min_stack.push(INT_MAX);}void push(int val) {x_stack.push(val);min_stack.push(min(min_stack.top(),val));}void pop() {x_stack.pop();min_stack.pop();}int top() {return x_stack.top();}int getMin() {return min_stack.top();}
};

有效的括号 (Hot 100)

有效的括号

class Solution {
public:bool isValid(string s) {if (s.size() % 2 != 0) return false;stack<char> st;for (int i = 0; i < s.size(); i++){if (s[i] == '(') st.push(')');else if (s[i] == '[')  st.push(']');else if (s[i] == '{') st.push('}');// 不匹配或者还没遍历完,栈为空// 注意,不能是(s[i] != st.top() ||st.empty()),因为空栈没有.top()else if (st.empty()||st.top() != s[i]) return false;else st.pop();}return st.empty();  // 栈为空,则有效}
};

字符串解码 (Hot 100)

字符串解码

class Solution {
public:string decodeString(string s) {stack<pair<string, int>> matchStack;string cur_str;int multi = 0;for (char& ch : s) {if (ch == '[') {matchStack.push({cur_str, multi});multi = 0;cur_str.clear();} else if (ch == ']') {auto [pre_str, cnt] = matchStack.top();matchStack.pop();  // pre_str是上个 [ 到当前 [ 的字符串,例如 "3[a2[c]]" 中的 a;for (int i = 0; i < cnt; i++)pre_str += cur_str; cur_str = pre_str;} else if (ch >= '0' and ch <= '9') {multi = multi * 10 + (int)(ch - '0');} elsecur_str += ch;}return cur_str;}
};

每日温度 (Hot 100)

每日温度

class Solution {  
public:  vector<int> dailyTemperatures(vector<int>& T) {  // 递增栈:存储温度序列中元素的索引,保证栈顶索引对应的温度从栈顶到栈底是递增的  stack<int> st;  // 结果数组,用于存储每天需要等待的天数,初始化为0  vector<int> result(T.size(), 0);  // 将第一个温度的索引压入栈中  st.push(0);  // 从第二个温度开始遍历温度序列  for (int i = 1; i < T.size(); i++) {  // 情况一:如果当前温度小于等于栈顶索引对应的温度  // 则将当前温度的索引压入栈中,因为栈中需要保持递增的温度  if (T[i] <= T[st.top()]) st.push(i);                          // 情况二:如果当前温度大于s栈顶索引对应的温度  // 则弹出栈顶索引,直到找到一个比当前温度更低的温度,或者栈为空  else {  while (!st.empty() && T[i] > T[st.top()]) {   // 更新栈顶索引需要等待的天数,为当前索引减去栈顶索引result[st.top()] = i - st.top();  st.pop();  }  st.push(i);  }  }  return result;  }  
};

简化:

class Solution {
public:vector<int> dailyTemperatures(vector<int>& T) {stack<int> st; // 递增栈vector<int> result(T.size(), 0);for (int i = 0; i < T.size(); i++) {while (!st.empty() && T[i] > T[st.top()]) { result[st.top()] = i - st.top();st.pop();}st.push(i);}return result;}
};

http://www.ppmy.cn/news/1531105.html

相关文章

OpenCV视频I/O(1)视频采集类VideoCapture介绍

操作系统&#xff1a;ubuntu22.04 OpenCV版本&#xff1a;OpenCV4.9 IDE:Visual Studio Code 编程语言&#xff1a;C11 算法描述 用于从视频文件、图像序列或摄像头捕获视频的类。 该类提供了用于从摄像头捕获视频或读取视频文件和图像序列的 C API。 以下是该类的使用方法&a…

【C高级】有关shell脚本的一些练习

目录 1、写一个shell脚本&#xff0c;将以下内容放到脚本中&#xff1a; 2、写一个脚本&#xff0c;包含以下内容&#xff1a; 1、写一个shell脚本&#xff0c;将以下内容放到脚本中&#xff1a; 1、在家目录下创建目录文件&#xff0c;dir 2、dir下创建dir1和dir2 …

Linux安装vim超详细教程

微服务Linux解析部署使用全流程 linux系统的常用命令 Linux安装JDK及配置环境变量超详细教程 Linux安装tomcat及配置环境变量超详细教程 1、vim 一个非常强大的文本编辑器。 Vim是一个类似于Vi的高度可定制的文本编辑器&#xff0c;在Vi的基础上改进和增加了很多特性。Vi…

聚簇索引和非聚簇索引——是什么?区别是什么?优缺点?

是什么? 聚簇索引&#xff1a;也叫主键索引&#xff0c;是将索引和数据放在一起&#xff0c;聚簇索引的 BTree 的叶子节点存放的是实际数据&#xff0c;所有完整的用户记录都存放在主键索引的 BTree 的叶子节点里&#xff1b;找到索引也就找到了数据。 非聚簇索引&#xff1a;…

宠物寄养系统小程序的设计

管理员账户功能包括&#xff1a;系统首页&#xff0c;个人中心&#xff0c;宠主管理&#xff0c;宠物种类管理&#xff0c;寄养环境管理&#xff0c;宠物寄养管理&#xff0c;系统管理 微信端账号功能包括&#xff1a;系统首页&#xff0c;寄养环境&#xff0c;我的 开发系统…

Python办公自动化教程(003):PDF的加密

【1】代码 from PyPDF2 import PdfReader, PdfWriter# 读取PDF文件 pdf_reader PdfReader(./file/Python教程_1.pdf) pdf_writer PdfWriter()# 对第1页进行加密 page pdf_reader.pages[0]pdf_writer.add_page(page) # 设置密码 pdf_writer.encrypt(3535)with open(./file/P…

Java面试篇基础部分- 锁详解

可重入锁 可重入锁也叫作递归锁,是指在同一个线程中,在外层函数获取到该锁之后,内存的递归函数还可以获取到该锁。在Java语言环境下,ReentrantLock和Synchroinzed都是可重入锁的代表。 公平锁与非公平锁 公平锁(Fair Lock)是指在分配锁之前检查是否有线程在排队等待获取…

Spring @Import

Import是Spring框架提供的注解org.springframework.context.annotation.Import&#xff0c;可以通过条件配置&#xff0c;选择性的注入哪些Bean到Spring IOC容器中&#xff1b; 一 Import注Bean到Spring容器 直接使用Import注解将Bean对象注入到容器 public class OrderChoi…