题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
解题思路:
- 将数组A放入栈中,放入之后与数组B进行判断
- 如果相等,则弹出,并且数组B索引往后移
- 当B索引到最后时,判断栈中是否为空
- 为空则说明B是正确的弹出序列,反之不是
代码:
/**
* @author: hyl
* @date: 2019/08/15
**/
public class Que21 {
public boolean IsPopOrder(int [] pushA,int [] popA) {
if (pushA == null || pushA.length == 0 ||
popA == null || popA.length == 0 || pushA.length != popA.length){
return false;
}
Stack<Integer> stack = new Stack<>();
int popIndex = 0;
for (int i = 0; i < pushA.length; i++) {
stack.push(pushA[i]);
while (!stack.isEmpty() && stack.peek() == popA[popIndex]){
//出栈
stack.pop();
popIndex++;
}
}
return stack.isEmpty();
}
}
代码地址:
https://github.com/Han-YLun/jianzhiOffer/blob/master/Solution/src/Que21.java
文章为阿伦原创,如果文章有错的地方欢迎指正,大家互相交流。