题目:
给定两个整数序列,第一个序列是栈的压入序列,判断第二个是不是栈的弹出序列?假设不重复,比如1,2,3,4,5和4,5,3,2,1
思路:
- 如果下一个弹出的数字刚好是栈顶数字,那么弹出。不在栈顶,持续压入,知道弹出的数字和栈顶一样,如果压完,还没找到,那么返回false。
代码:
boolean isPopOrder(int[] push,int[] pop,int length){
boolean possible = false;
int i = 0;
int j = 0;
Stack<Integer> data = new Stack<Integer>();
while(j < length){
while(data.empty() || data.top != pop[j]){
if(i >= length){
break;
}
data.push(push.[i]);
i++;
}
if(data.top != pop[j]){
break;
}
data.pop();
j++;
}
if(data.empty() && j == length){
possible = true;
}
return possible;
}