LeetCode 题解工作台
验证栈序列
给定 pushed 和 popped 两个序列,每个序列中的 值都不重复 ,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列的结果时,返回 true ;否则,返回 false 。 示例 1: 输入: pushed = [1,2,3,4,5], popped = [4,5,3…
3
题型
8
代码语言
3
相关题
当前训练重点
中等 · 栈·状态
答案摘要
我们遍历 数组,对于当前遍历到的元素 ,我们将其压入栈 中,然后判断栈顶元素是否和 数组中下一个要弹出的元素相等,如果相等,我们就将栈顶元素弹出并将 数组中下一个要弹出的元素的索引 加一。最后,如果要弹出的元素都能按照 数组的顺序弹出,返回 ,否则返回 。 时间复杂度 ,空间复杂度 。其中 为 数组的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路
题目描述
给定 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:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
stk = []
i = 0
for x in pushed:
stk.append(x)
while stk and stk[-1] == popped[i]:
stk.pop()
i += 1
return i == len(popped)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) since each element is pushed and popped at most once. Space complexity is O(n) to store the stack in the worst case, proportional to the length of the pushed array. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Looking for clear stack simulation and pointer usage.
- question_mark
Expect recognition that element order in pushed matters.
- question_mark
Watch for correct handling of stack top matching popped elements.
常见陷阱
外企场景- error
Attempting to pop elements in an order not allowed by the stack.
- error
Forgetting to check stack top against the current popped element repeatedly.
- error
Assuming sequences are valid without simulating push and pop accurately.
进阶变体
外企场景- arrow_right_alt
Sequences where pushed and popped include duplicate values.
- arrow_right_alt
Larger arrays requiring optimized in-place simulation.
- arrow_right_alt
Generating the valid popped sequence given a random pushed array.