题目:
思路:
- 先遍历将pushA里的元素入栈
- 当栈不为空,且栈顶元素与popA中元素相等时,将栈顶元素出栈,再比较popA的下一个元素和新的栈顶元素
- 当pushA里的元素遍历结束,且辅助栈中元素为空,则代表true反之false
代码:
//栈的压入弹出序列
public boolean IsPopOrder(int [] pushA,int [] popA) {
Stack<Integer> stack = new Stack<>();
//先对非法条件进行限制
if (pushA.length == 0 || popA.length == 0 || popA.length != pushA.length){
return false;
}
int j = 0;
//遍历pushA元素入栈
for (int i = 0;i < pushA.length;i++) {
stack.push(pushA[i]);
//当栈顶元素等于popA中元素时,则出栈
//出现了空栈异常,所以要在这里加上空栈判断
while ( !stack.isEmpty() && stack.peek() == popA[j] ) {
stack.pop();
//比较当前栈顶元素和popA的下一个元素
j++;
}
}
//上循环结束后,若辅助栈为空,则为true,不为空,则返回false
return stack.isEmpty();
}