当前位置:网站首页>946. 验证栈序列
946. 验证栈序列
2022-07-05 12:39:00 【厚积薄发ض】
给定 pushed 和 popped 两个序列,每个序列中的 值都不重复,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列的结果时,返回 true;否则,返回 false 。
示例 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 之前弹出。
提示:
1 <= pushed.length <= 10000 <= pushed[i] <= 1000pushed的所有元素 互不相同popped.length == pushed.lengthpopped是pushed的一个排列
我们做法是先将进栈序列入栈,当出栈序列与入栈序列相同的时候,栈顶元素要出栈,同时出栈序列接着遍历下一个元素
这是相同的情况:

这是不同的情况:

思路:
让入栈队列一一入栈,看栈顶元素是否与出栈队列元素相同,如果不相同,依次让入栈队列一一入栈,如果相同就让栈顶元素出栈,同时出栈队列遍历下一个元素,继续往复循环,最后如果入栈数组遍历完成并且栈为空就证明入栈队列与出栈队列是相同的,如果最后入栈数组遍历完成而栈不为空,那就证明入栈队列与出栈队列不相同。
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> s = new Stack<Integer>();
int index = 0;
for(int i = 0 ; i < pushed.length; i ++){
s.push(pushed[i]);//将入栈序列压栈
while(!s.isEmpty() && index<popped.length&&popped[index] == s.peek()){
//在栈不为空的情况下并且index不越界看出栈序列是否与栈顶元素相同
s.pop();//如果相同弹出栈顶元素
index++;//遍历下一个元素
}
}
return s.isEmpty();
}
}边栏推荐
- 非技术部门,如何参与 DevOps?
- Add a new cloud disk to Huawei virtual machine
- Resnet+attention project complete code learning
- About LDA model
- RHCSA7
- Pytoch uses torchnet Classerrormeter in meter
- Distance measuring sensor chip 4530a used in home intelligent lighting
- Transactions on December 23, 2021
- Pytoch implements tf Functions of the gather() function
- Insmod prompt invalid module format
猜你喜欢

Laravel文档阅读笔记-mews/captcha的使用(验证码功能)

【Nacos云原生】阅读源码第一步,本地启动Nacos

Shi Zhenzhen's 2021 summary and 2022 outlook | colorful eggs at the end of the article

OPPO小布推出预训练大模型OBERT,晋升KgCLUE榜首

I met Tencent in the morning and took out 38K, which showed me the basic smallpox

DNS的原理介绍

SAP UI5 DynamicPage 控件介绍

Kotlin变量

初识Linkerd项目

JDBC exercise - query data encapsulated into object return & simple login demo
随机推荐
上午面了个腾讯拿 38K 出来的,让我见识到了基础的天花
单独编译内核模块
以VMware创新之道,重塑多云产品力
A few years ago, I outsourced for four years. Qiu Zhao felt that life was like this
10 minute fitness method reading notes (2/5)
Resnet18 actual battle Baoke dream spirit
OPPO小布推出预训练大模型OBERT,晋升KgCLUE榜首
10 minute fitness method reading notes (3/5)
Using docker for MySQL 8.0 master-slave configuration
Transactions from December 27 to 28, 2021
Common commands and basic operations of Apache Phoenix
Docker configures redis and redis clusters
[cloud native] event publishing and subscription in Nacos -- observer mode
SAP SEGW 事物码里的 ABAP Editor
Kotlin variable
How do e-commerce sellers refund in batches?
关于 SAP UI5 getSAPLogonLanguage is not a function 的错误消息以及 API 版本的讨论
Taobao order interface | order flag remarks, may be the most stable and easy-to-use interface
Pytoch monolayer bidirectional_ LSTM implements MNIST and fashionmnist data classification
我在滴滴做开源