算法1
(辅助栈) $O(n)$
用一个辅助栈来模拟进栈
通过判断pop数组和栈顶的关系,来判断是否是弹出序列,如果pop数组当前的数和栈顶相同,栈顶弹出,pop数组下一个数,如果不同,压入push数组的下一个数值
如果push数组全部压入,pop数组当前数值依然不相同,则返回false;
java 代码
class Solution {
public boolean isPopOrder(int [] push,int [] pop) {
boolean is = false;
int len = push.length;
if(len!=pop.length)
return is;
if(len==0&&pop.length==0)
return true;
if(push!=null&&pop!=null&&len>0){
Stack<Integer> stack = new Stack<>();
stack.push(push[0]);
int j = 1;
for(int i =0;i<pop.length;i++){
if(stack.empty()){
stack.push(push[j]);
j++;
}
while(pop[i]!=stack.peek()&&j<push.length){
stack.push(push[j]);
j++;
}
if(stack.peek()!=pop[i]&&j>=push.length){
return false;
}
stack.pop();
}
is = true;
}
return is;
}
}