LC 946. 验证栈序列

题目描述

这是 LeetCode 上的 946. 验证栈序列 ,难度为 中等

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

示例 1:

1
2
3
4
5
6
7
输入: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:
1
2
3
4
5
输入: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 的一个排列

栈运用模拟

根据题意,利用元素各不相同,我们使用一个栈来处理 pushed 数组,每次将 $pushed[i]$ 放入栈中,然后比较当前栈顶元素是否与待弹出元素相同(使用变量 j 来代指当前待弹出元素下标),若相等则弹栈并进行 j 自增,当所有的元素处理完后,栈为空说明栈序列合法。

Java 代码:

1
2
3
4
5
6
7
8
9
10
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Deque<Integer> d = new ArrayDeque<>();
for (int i = 0, j = 0; i < pushed.length; i++) {
d.addLast(pushed[i]);
while (!d.isEmpty() && d.peekLast() == popped[j] && ++j >= 0) d.pollLast();
}
return d.isEmpty();
}
}

Typescript 代码:
1
2
3
4
5
6
7
8
9
function validateStackSequences(pushed: number[], popped: number[]): boolean {
let n = pushed.length, he = 0, ta = 0
const stk: number[] = new Array<number>(n).fill(0)
for (let i = 0, j = 0; i < n; i++) {
stk[ta++] = pushed[i]
while (he < ta && stk[ta - 1] == popped[j] && ++j >= 0) ta--
}
return he == ta
};

  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$

双指针

我们也可以直接利用 pushed 充当栈,使用变量 idx 代指栈顶下标,变量 j 指向 popped 中待弹出的元素。

该做法好处无须额外空间,坏处是会修改入参数组。

Java 代码:

1
2
3
4
5
6
7
8
9
10
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
int n = pushed.length, idx = 0;
for (int i = 0, j = 0; i < n; i++) {
pushed[idx++] = pushed[i];
while (idx > 0 && pushed[idx - 1] == popped[j] && ++j >= 0) idx--;
}
return idx == 0;
}
}

TypeScript 代码:
1
2
3
4
5
6
7
8
function validateStackSequences(pushed: number[], popped: number[]): boolean {
let n = pushed.length, idx = 0
for (let i = 0, j = 0; i < n; i++) {
pushed[idx++] = pushed[i]
while (idx > 0 && pushed[idx - 1] == popped[j] && ++j >= 0) idx--
}
return idx == 0
};

  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(1)$

加餐

加餐一道同类型题目 : 常规栈运用题🎉🎉


最后

这是我们「刷穿 LeetCode」系列文章的第 No.946 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。

在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。

为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSource/LogicStack-LeetCode

在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!