友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
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.
Note:
-
0 ⇐ pushed.length == popped.length ⇐ 1000
-
0 ⇐ pushed[i], popped[i] < 1000
-
pushed
is a permutation ofpopped
. -
pushed
andpopped
have distinct values.
思路分析
模拟栈的操作
-
一刷
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @author D瓜哥 · https://www.diguage.com
* @since 2024-09-13 20:29:14
*/
public boolean validateStackSequences(int[] pushed, int[] popped) {
Deque<Integer> stack = new LinkedList<>();
int oi = 0;
for (int i = 0; i < pushed.length; i++) {
int inum = pushed[i];
stack.addLast(inum);
while (!stack.isEmpty() && stack.peekLast() == popped[oi]) {
stack.removeLast();
oi++;
}
}
return stack.isEmpty();
}