当前位置:网站首页>剑指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 <= 10000 <= pushed[i], popped[i] < 1000pushed是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();
}
}
边栏推荐
猜你喜欢
随机推荐
【Connect the heart rate sensor to Arduino to read the heart rate data】
Case | industrial iot solutions, steel mills high-performance security for wisdom
联阳IT6561|IT6561FN方案电路|替代IT6561方案设计DP转HDMI音视频转换器资料
VCA821可变增益放大器
TQP3M9009电路设计
剑指Offer 47.礼物的最大值 动态规划
LT9211芯片资料分享
Lightly:新一代的C语言IDE
GM8775C MIPI转LVDS调试资料分享
使用飞凌嵌入式IMX6UL-C1板子——qt+opencv环境搭建
步兵相关连接
rosdep update失败解决办法(亲测有效)
MQ-5 combustible gas sensor interface with Arduino
【plang 1.4.4】编写贪吃蛇脚本
GM8775C规格书,MIPI转LVDS,MIPI转双路LVDS分享
将ORCAD原理图导入allegro中进行PCB设计
Beckhoff ET2000 listener use
增量编译技术在Lightly中的实践
分割回文串 DP+回溯 (LeetCode-131)
发布全新的配置格式 - AT




![开源日志库 [log4c] 使用](/img/f5/cce26f5820155c537f2cd975bafbcd.png)




