题号:剑指 Offer 31
题目名:栈的压入、弹出序列
原题URL:https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/
题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。
示例
示例 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 之前弹出。
限制
-
0 <= pushed.length == popped.length <= 1000
-
0 <= pushed[i], popped[i] < 1000
-
pushed 是 popped 的排列。
思路
1.栈是先入后出的,要保证满足pop的序列的话,最好的办法就是一遇到入栈元素等于该出栈的时候,就将它出栈
2.遇到相等元素的时候,开始按pop数组出栈
3.出栈到最后,如果还剩余元素,说明还没有出栈完全,不能弹出
解题代码
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
//栈的数据结构是先入后出,要保证pop能够弹出,那么就当入栈元素等于当前位置元素的时候,就立马出栈
Stack<Integer> stack = new Stack<>();
//记录弹栈的位置
int popIdx = 0;
for (int i = 0; i < pushed.length; i++) {
stack.push(pushed[i]);
while (!stack.isEmpty()&&stack.peek()==popped[popIdx]) {
stack.pop();
popIdx++;
}
}
return stack.isEmpty();
}
}