Problem
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:
1 | Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1] |
Example 2:
1 | Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2] |
Constraints:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed
is a permutation ofpopped
.pushed
andpopped
have distinct values.
Analysis
这是一道和stack相关的题目。题目给出两个数组pushed
和popped
,要求我们校验能否从pushed
数组,通过一个stack,产生出popped
数组。思路也很清晰,直接用一个stack模拟即可。把pushed
中的元素逐个放入到stack中,每次放入后,和popped
中的做对比,如果栈顶元素和popped
中的相同,元素出栈,popped
的下标自增,如果到最后栈为空并且popped
的下标到了末尾,说明所有的元素都能处理完,return true;否则return false。
Solution
无
Code
1 | class Solution { |
Summary
这道题目是栈的利用,它从另一个角度考察了我们对栈的理解。这道题目的分享到这里,谢谢您的支持!