946. 验证栈序列
946. 验证栈序列
题目
Given two integer arrays pushed
and popped
each with distinct values, return true
if this could have been the result of a sequence of push and pop operations on an initially empty stack, orfalse
otherwise.
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:
1 <= pushed.length <= 1000
0 <= pushed[i] <= 1000
- All the elements of
pushed
are unique. popped.length == pushed.length
popped
is a permutation ofpushed
.
题目大意
给定 pushed
和 popped
两个序列,每个序列中的 值都不重复,只有当它们可能是在最初空栈上进行的推入 push
和弹出 pop
操作序列的结果时,返回 true
;否则,返回 false
。
解题思路
这道题可以使用模拟栈的方法进行判断,使用一个辅助栈 stack
,模拟 push
和 pop
操作,最后通过判断栈是否为空来得到最终的结果。
具体思路如下:
- 遍历
pushed
数组,模拟入栈操作,并在每次入栈后,判断是否需要执行出栈操作。 - 如果当前栈顶元素等于
popped
数组中下一个要出栈的元素,则执行出栈操作。 - 遍历结束后,判断栈是否为空。
代码