当前位置:网站首页>剑指Offer 31.栈的压入、弹出
剑指Offer 31.栈的压入、弹出
2022-08-02 03:33:00 【HotRabbit.】
题目
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。
示例 1:
输入: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
示例 2:
输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
输出:false
解释:1 不能在 2 之前弹出。
提示:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed
是popped
的排列。
思路
借助一个栈循环压入元素,每次压入元素,都要进行一个循环判断是否可以弹出。返回栈是否为空。
题解
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
int l = pushed.length;
Stack<Integer> stack = new Stack<>();
int i = 0;
for (int num : pushed) {
stack.push(num);
while (!stack.isEmpty() && stack.peek() == popped[i]){
stack.pop();
i++;
}
}
return stack.isEmpty();
}
}
边栏推荐
- 【plang 1.4.6】Plang高级编程语言(发布)
- Lightly:新一代的C语言IDE
- 使用飞凌嵌入式IMX6UL-C1板子——qt+opencv环境搭建
- 为什么D类音频功放可以免输出滤波器
- 步兵相关连接
- Arduino lights up nixie tubes
- [Arduino uses a rotary encoder module]
- 使用buildroot制作根文件系统(龙芯1B使用)
- Comparative analysis of mobile cloud IoT pre-research and Alibaba Cloud development
- 2019 - ICCV - 图像修复 Image Inpainting 论文导读《StructureFlow: Image Inpainting via Structure-aware ~~》
猜你喜欢
开源代码交叉编译操作流程及遇到的问题解决(lightdm)
Chrome 里的小恐龙游戏是怎么做出来的?
Altium Designer基础知识
USB3.0一致性测试方法
【多线程】线程安全保护机制
Comparative analysis of mobile cloud IoT pre-research and Alibaba Cloud development
2020 - AAAI - Image Inpainting论文导读《Learning to Incorporate Structure Knowledge for Image Inpainting》
【LeetCode】合并
VCA821可变增益放大器
使用飞凌嵌入式IMX6UL-C1板子——qt+opencv环境搭建
随机推荐
模拟电子技术------半导体
哈希表解题方法
联阳IT6561|IT6561FN方案电路|替代IT6561方案设计DP转HDMI音视频转换器资料
Lightly 支持 Markdown 文件在线编写(文中提供详细 Markdown 语法)
【数据库】事务的四大特性<详解>
GM7150 CVBS转BT656视频解码芯片详细内容及设计要求
电子密码锁_毕设‘指导’
判断子序列 —— LeetCode-392
Basic IO (on): file management and descriptors
VCA821可变增益放大器
字符串匹配(蛮力法+KMP)
同时求最大值与最小值(看似简单却值得思考~)
GM8284DD,GM8285C,GM8913,GM8914,GM8905C,GM8906C,国腾振芯LVDS类芯片
GM8775C规格书,MIPI转LVDS,MIPI转双路LVDS分享
Laptop charging problems
Industry where edge gateway strong?
Based on the raspberry pie smart luggage development environment set up
The use and simulation of vector implementation:
rosdep update失败解决办法(亲测有效)
C语言教程 - 制作单位转换器