考虑借用一个辅助栈 stack,模拟 压入 / 弹出操作的排列。根据是否模拟成功,即可得到结果。
算法流程:
- 初始化: 辅助栈 stack,弹出序列的索引 idx;
- 遍历压栈序列: 各元素记为 num;
元素 num 入栈;
循环出栈:若 stack 的栈顶元素 == 弹出序列元素 popped[idx],则执行出栈与 idx++; - 返回值: 若 stack 为空,则此弹出序列合法
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
Stack<Integer> stack = new Stack<>();
int idx = 0;
for(int num: pushA){
stack.push(num);
while(!stack.isEmpty() && stack.peek() == popA[idx]){
stack.pop();
idx++;
}
}
return stack.isEmpty();
}
}