输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。
例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。
思路:
添加一个辅助栈,将压入序列依次放入栈中,然后按照弹出序列取出栈中元素,若压入序列放入栈完毕,栈顶元素还不是弹出序列的元素,则该弹出序列不正确。
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
if(null==pushA || null==popA || pushA.length==0 || popA.length==0 || pushA.length!=popA.length){
return false;
}else{
Stack<Integer> s = new Stack<Integer>();
int iPush = 0;
int iPop = 0;
while(iPop < popA.length){
while((iPush<pushA.length) && (s.empty() || s.peek()!=popA[iPop])){
s.push(pushA[iPush]);
iPush++; //指向pushA下一个元素
}
if(s.peek() == popA[iPop]){
s.pop();
iPop++; //指向popA下一个元素
}
else{
return false;
}
}
return true; //全部匹配完毕时,返回true
}
}
}