LeetCode 题解工作台

验证栈序列

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

category

3

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

中等 · 栈·状态

bolt

答案摘要

我们遍历 数组,对于当前遍历到的元素 ,我们将其压入栈 中,然后判断栈顶元素是否和 数组中下一个要弹出的元素相等,如果相等,我们就将栈顶元素弹出并将 数组中下一个要弹出的元素的索引 加一。最后,如果要弹出的元素都能按照 数组的顺序弹出,返回 ,否则返回 。 时间复杂度 ,空间复杂度 。其中 为 数组的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定 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 <= 1000
  • 0 <= pushed[i] <= 1000
  • pushed 的所有元素 互不相同
  • popped.length == pushed.length
  • poppedpushed 的一个排列
lightbulb

解题思路

方法一:栈模拟

我们遍历 pushed\textit{pushed} 数组,对于当前遍历到的元素 xx,我们将其压入栈 stk\textit{stk} 中,然后判断栈顶元素是否和 popped\textit{popped} 数组中下一个要弹出的元素相等,如果相等,我们就将栈顶元素弹出并将 popped\textit{popped} 数组中下一个要弹出的元素的索引 ii 加一。最后,如果要弹出的元素都能按照 popped\textit{popped} 数组的顺序弹出,返回 true\textit{true},否则返回 false\textit{false}

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nnpushed\textit{pushed} 数组的长度。

1
2
3
4
5
6
7
8
9
10
11
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)
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

验证栈序列题解:栈·状态 | LeetCode #946 中等