给定两个序列,pushed和popped(里面每个值都不同),如果这两个序列能真实对应着某种入栈出栈顺序则返回true,否则返回false.
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 of popped.
- pushed and popped have distinct values.
思路分析:
既然题目问这能不能模拟真实栈的操作,那么我们就用栈来模拟一下,如果最后栈为空,那说明这确实是真实的操作。
我们用两个指针i,j分别对应push和pop序列
如果push[i] != pop[j]
,那么stack.append(push[i])
如果pop[j] == stack[-1]
,那么stack.pop()
最后判断stack
是否为空
1 | class Solution(object): |