当前位置:网站首页>判断某个序列是否为栈的弹出序列
判断某个序列是否为栈的弹出序列
2022-06-26 18:01:00 【一只懐坏旭】
一,题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
二,题目分析
题中给出的两个序列,一个是入栈序列,一个是出栈序列。
在保证入栈序列的有序性的情况下,入栈出栈的交替顺序,导致出栈序列有不同的顺序的序列。
解题思路:
- 1.如果弹入或者弹出序列有一个为空,直接返回false
- 2.用一个辅助栈来保存入栈序列,一个标记变量来定位弹出序列的元素位置
- 3.循环入栈,外层循环中(遍历入栈序列),再循环对比(while),如果s栈不为空且此时栈顶元素等于弹出序列popIndex位,就持续出栈
- 4,最终如果辅助栈为空,就说明是该入栈序列的出栈方式中的一种返回true,不为空则不是,直接返回false
三,上代码(看注释!!!)
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
if(pushA.length == 0 || popA.length == 0){
//如果弹入或者弹出序列有一个为空
return false;
}
Stack<Integer> s = new Stack<>(); //用来组织弹入序列中的元素
int popIndex = 0; //用来标记该弹出的位置的元素在序列中的位置
for(int i = 0; i < pushA.length;i++){
//循环遍历弹入序列,依次放入栈s
s.push(pushA[i]);
while(!s.isEmpty() && s.peek() == popA[popIndex]){
//如果s栈不为空且此时栈顶元素等于弹出序列popIndex位
//此处循环是核心,判断是否为很多出栈顺序中的一个
//出栈
s.pop();
//pop位后移
popIndex++;
}
}
//循环结束,如果栈s为空,就说明是该入栈序列的的一个弹出序列
return s.isEmpty();
}
}边栏推荐
- Using redis for user access data statistics hyperloglog and bitmap advanced data types
- 解决pycharm里面每个字母占一格空格的问题
- vutils. make_ A little experience of grid () in relation to black and white images
- 陈强:阿里千亿级大规模数字商业知识图谱助力业务增长
- Discussion and generation of digital signature and analysis of its advantages
- 【代码随想录-动态规划】T583、两个字符串的删除操作
- 数字签名标准(DSS)
- RSA加密解密详解
- in和exsits、count(*)查询优化
- How does Guosen Securities open an account? Is it safe to open a stock account through the link
猜你喜欢

properties文件乱码

丰富专业化产品线, 江铃福特领睿·极境版上市

让torch.cuda.is_available()从false变成true的一点经验

并发之Synchronized说明

transforms. The input of randomcrop() can only be PIL image, not tensor

行锁与隔离级别案例分析

Detailed explanation of dos and attack methods

背包问题求方案数

【万字总结】以终为始,详细分析高考志愿该怎么填

transforms.RandomCrop()的输入只能是PIL image 不能是tensor
随机推荐
Let torch cuda. is_ Experience of available() changing from false to true
Applet setting button sharing function
How to open a stock account? Is it safe to open an account online now?
halcon之区域:多种区域(Region)特征(5)
Prometeus 2.34.0 new features
Uncover the secret of Agora lipsync Technology: driving portraits to simulate human speech through real-time voice
如何将应用加入到deviceidle 白名单?
Hello, is it safe to open an online stock account and buy stocks now?
JNI的 静态注册与动态注册
QPushButton 样式使用示例(以及按钮setmenu添加下拉菜单的方法)
in和exsits、count(*)查询优化
Solve the problem that each letter occupies a space in pycharm
贝叶斯网络详解
Use FST JSON to automatically generate faster JSON serialization methods
[dynamic planning] Jianzhi offer II 091 Paint the house
RSA加密解密详解
行锁分析和死锁
Detailed explanation of asymmetric cryptosystem
Knapsack problem with dependency
17.13 补充知识、线程池浅谈、数量谈、总结