因为可能没全部压入就弹出一部分,所以我们可以模拟这个过程。
for循环压入是一定的,在每个循环里面根据弹出序列的头部是不是栈顶元素来判断是否弹出了,每次判断后序列往下走一步,栈也弹出一个,最后根据栈是否为空判断是否可能。
代码如下:
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
Stack<Integer> stack = new Stack<Integer>();
for(int i = 0,j = 0;i < pushA.length;i++){
stack.push(pushA[i]);
while(!stack.isEmpty() && j < popA.length && stack.peek() == popA[j]){
stack.pop();
j++;
}
}
return stack.empty();
}
public static void main(String[] args) {
int [] arr1 = {3,5,1,2,4};
int [] arr2 = {1,5,3,4,2};
System.out.println(new Solution().IsPopOrder(arr1, arr2));
}
}
最后别忘了while中的第一个条件(注意用isEmpty()函数而不是跟null比较),防止为空时的peek操作导致空指针异常。