输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。
思路:具体思路见剑指offer
代码如下;
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
boolean isPossiable = false;
if(pushA==null||popA==null||pushA.length==0|popA.length==0) return isPossiable;
if(pushA.length!=popA.length) return isPossiable;
int j = 0;
int i = 0;
Stack<Integer> stack = new Stack<Integer>();
for(;i<pushA.length;i++){
stack.push(pushA[i]);
while(!stack.empty() && stack.peek()==popA[j]){
stack.pop();
j++;
}
}
if(stack.empty()){
isPossiable =true;
}
return isPossiable;
}
}
值得注意的是while(
!stack.empty()
&& stack.peek()==popA[j]),必须加上这个判断条件,因为调用peek()时,栈不能是空的。
参考博客:http://www.cnblogs.com/kaituorensheng/p/3618339.html