LeetCode 946. 验证栈序列(Validate Stack Sequences) 26
2024-10-21 14:20:02
946. 验证栈序列
946. Validate Stack Sequences
题目描述
Given two sequences pushed and popped with distinct values, return true if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.
每日一算法2019/5/29Day 26LeetCode946. Validate Stack Sequences
Example 1:
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
Example 2:
Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.
Output: false
Explanation: 1 cannot be popped before 2.
Note:
- 0 <= pushed.length == popped.length <= 1000
- 0 <= pushed[i], popped[i] < 1000
- pushed is a permutation of popped.
- pushed and popped have distinct values.
Java 实现
import java.util.Stack;
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
int n = pushed.length;
Stack<Integer> stack = new Stack<>();
for (int pushIndex = 0, popIndex = 0; pushIndex < n; pushIndex++) {
stack.push(pushed[pushIndex]);
while (popIndex < n && !stack.isEmpty() && stack.peek() == popped[popIndex]) {
stack.pop();
popIndex++;
}
}
return stack.isEmpty();
}
}
参考资料
- https://leetcode-cn.com/problems/validate-stack-sequences/
- https://leetcode.com/problems/validate-stack-sequences/
最新文章
- TODO:小程序开发过程之体验者
- Boost学习笔记(三) progress_timer
- DeepLearning入门笔记(一),准备工作与注意事项
- w3m浏览器 for Linux
- cocos2dx游戏开发——别踩白块学习笔记(一)——Block类
- Swift3.0语言教程字符串与URL的数据转换与自由转换
- 基础笔记5(file)
- NHibernate学习笔记
- Extjs发票管理系统
- jquery序列化form表单使用ajax提交后处理返回的json数据
- 移动端的click
- linux核心之进程管理
- 机器学习:Python中如何使用最小二乘法
- php lcg_value与mt_rand生成0~1随机小数的效果比较
- linux中监控CPU、内存和磁盘状态的shell脚本。(centos7)
- Centos 7内核3升级到4
- Python接口自动化【requests处理Token请求】
- 转【面向代码】学习 Deep Learning(二)Deep Belief Nets(DBNs)
- uva-529-枚举
- nodejs服务器部署教程四
热门文章
- tensorflow API _ 3 (tf.train.polynomial_decay)
- [HTML5] Using HTMLPortalElement to improve MPA preformance
- 持续集成学习5 jenkins自动化测试与构建
- java代码操作Redis
- Python 08 skimage
- Theano入门笔记2:scan函数等
- mysql 数据插入insert
- .getCellType()的几种类型值
- java内存dump文件导出与查看
- 大数据 | 分布式文件系统HDFS 练习