其他分享
首页 > 其他分享> > [LeetCode] 946. Validate Stack Sequences

[LeetCode] 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.

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:

验证栈序列。

给定 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