剑指offer-面试题22-栈的压入、弹出序列

来源:互联网 发布:北京淘宝纸箱 企业05 编辑:程序博客网 时间:2024/06/01 10:52

题目描述:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压栈序列,序列4,5,3,2,1是该栈的一个弹出序列,4,3,5,1,2则不可能是弹出序列。

题目分析:可以借助辅助栈,通过一个一个向栈中加入压栈序列中的元素,每次压入都跟出栈序列中元素作比较,如果相等,则弹出,同时出栈序列下标后移。

//栈的压入和弹出    public static boolean isPopOrder(int[] push, int[] pop) {        if (push == null || pop == null || push.length < 1 || pop.length < 1 || push.length != pop.length) {            return false;        }        Stack<Integer> stack = new Stack<>();        int pushIndex = 0, popIndex = 0;//pushIndex为入栈数组处理的位置,popIndex用来记录出战数组的处理位置        while (popIndex < pop.length) {//使用出栈序列来做循环判断            while (pushIndex < push.length) {                if (stack.isEmpty() || stack.peek() != pop[popIndex]) {//如果栈中为空或者栈顶元素不等于出栈序列的元素                    stack.push(push[pushIndex]);//入栈                    pushIndex++;                } else {//如果栈不为空,并且栈顶元素==出栈序列元素,跳出循环                    break;                }            }            if (stack.peek() == pop[popIndex]) {                popIndex++;                stack.pop();            } else {                return false;            }        }        return true;    }

或者如下代码来自http://blog.csdn.net/google19890102/article/details/40264699

public static boolean isPopOrder(int pushArray[], int popArray[]) {          boolean flag = false;          // 能够执行的条件是这样的序列不为空,而且两个序列的长度是相等的          if (pushArray.length > 0 && pushArray.length == popArray.length) {              // 构造一个辅助栈,模拟入栈和出栈              Stack<Integer> stack = new Stack<Integer>();              int i = 0;              int j = 0;              // 保证入栈序列全进入栈              while (i < pushArray.length) {                  // 当栈非空时,若栈顶元素与出栈序列中的元素相同,则出栈                  if (stack.size() > 0 && stack.peek() == popArray[j]) {                      stack.pop();                      j++;                  } else {// 若不相同或者栈为空,则在入栈序列中继续增加                      stack.push(pushArray[i]);                      i++;                  }              }              // 此时栈中还有元素需要与出栈序列对比              while (stack.size() > 0) {                  // 若果相等就出栈                  if (stack.peek() == popArray[j]) {                      stack.pop();                      j++;                  } else {//若不相等就直接退出                      break;                  }              }              // 最终如果栈是空的,而且popArray中的所有数都遍历了,则是出栈序列              if (stack.isEmpty() && j == popArray.length) {                  flag = true;              }          }          return flag;      }  
0 0
原创粉丝点击