Acwing_42 栈的压入、弹出序列
解题思路:
1、如果当前压入辅助栈helpStack的栈顶元素的值与弹出序列的index下标所指的元素的值相同,那么将辅助栈的栈顶元素弹出,并且index++,向后移动一位
2、如果当前压入辅助栈helpStack的栈顶元素的值与弹出序列的index下标所指的元素的值不相同,那么继续将压入序列中的元素压入辅助栈中,直到相同为止
3、如果最终辅助栈中为空,没有任何元素则返回true
public class A_42 {
private static Stack<Integer> helpStack = new Stack<Integer>(); //辅助栈
public static void main(String[] args) {
A_42 a_42 = new A_42();
int[] pushArr = {1,2,3,4,5};
int[] popArr = {4,5,3,2,1};
int[] push = {8,2,7,4,5};
int[] pop = {7,5,2,8,4};
System.out.println(a_42.isPopOrder(pushArr, popArr));
System.out.println(a_42.isPopOrder(push, pop));
}
public boolean isPopOrder(int [] pushV,int [] popV) {
//若两个序列长度不等则视为并不是一个栈的压入、弹出序列
if (pushV.length != popV.length){
return false;
}
//若两个序列都为空,则视为是一个栈的压入、弹出序列
if (pushV.length == 0 && popV.length == 0){
return true;
}
int index = 0;
for (int i = 0; i < pushV.length; i++){
helpStack.push(pushV[i]);
//辅助栈不为空 且 辅助栈的栈顶元素与弹出序列的中index下标所对应的值相同
while (!helpStack.isEmpty() && helpStack.peek() == popV[index]){
helpStack.pop();
index ++;
}
}
return helpStack.isEmpty();
}
}
运行结果: