ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[LeetCode] 946. Validate Stack Sequences

2021-02-28 08:32:06  阅读:400  来源: 互联网

标签:popped 946 元素 pop pushed Sequences push Validate stack


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.

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

Example 2:

Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.

Constraints:

  • 0 <= pushed.length == popped.length <= 1000
  • 0 <= pushed[i], popped[i] < 1000
  • pushed is a permutation of popped.
  • pushed and popped have distinct values.

验证栈序列。

给定 pushed 和 popped 两个序列,每个序列中的 值都不重复,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列的结果时,返回 true;否则,返回 false 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/validate-stack-sequences
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是模拟元素入栈出栈的过程,如果过程中有元素对不上则返回false。我们创建一个stack,根据 pushed 数组的顺序把元素放到 stack 中。每次我们把一个元素放到 stack 之后,我们需要检查一下,如果当前栈顶元素 == popped[i] 说明当前栈顶这个元素是要被pop出来的。如果当前栈顶元素 != popped[i] 则说明对不上了。按照这个模拟的顺序,stack应该是为空的,所以如果模拟结束之后stack不为空,则返回false。

时间O(n)

空间O(n)

Java实现

 1 class Solution {
 2     public boolean validateStackSequences(int[] pushed, int[] popped) {
 3         int i = 0;
 4         Stack<Integer> stack = new Stack<>();
 5         for (int num : pushed) {
 6             stack.push(num);
 7             while (!stack.isEmpty() && popped[i] == stack.peek()) {
 8                 stack.pop();
 9                 i++;
10             }
11         }
12         return stack.isEmpty();
13     }
14 }

 

LeetCode 题目总结

标签:popped,946,元素,pop,pushed,Sequences,push,Validate,stack
来源: https://www.cnblogs.com/cnoodle/p/14458094.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有