JavaScript版《剑指offer》刷题(20)栈的压入、弹出序列

1.题目描述

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)。

2.题目分析

思路

借用一个辅助的栈,将原数列依次压入辅助栈,栈顶元素与所给的出栈队列相比,如果相同则出栈;
如果不同则继续压栈,知道原数列中所有的数字压栈完毕;
检测辅助栈中是否为空, 若空,则该序列是压栈序列对应的一个弹出序列。否则,说明序列不是该栈的弹出序列。

举例

入栈:1,2,3,4,5
出栈:4,5,3,2,1
1) 1入辅助栈,此时1≠4;
2) 2入辅助栈,此时2≠4;
3) 3入辅助栈,此时3≠4;
4) 4入辅助栈,此时4=4,辅助栈出栈,剩下 1,2,3;同时,弹出序列向后一位,为5;此时3≠5,继续压栈;
5) 5入辅助栈,此时5=5,辅助栈出栈,剩下1,2,3;同时,弹出序列向后一位,为3;
6) 此时3=3,辅助栈出栈,剩下1,2;同时弹出序列向后一位,为2;
7) 此时2=2,辅助栈出栈,剩下1;同时弹出序列向后一位,为1;
8) 此时1=1,辅助栈出栈,为空,所以该序列是压栈序列对应的一个弹出序列。


3.代码

// 第一种
function IsPopOrder(pushV, popV) {
  // write code here
  const helpStack = [];
  let flag = false;
  while (pushV.length || helpStack.length) {
    while (helpStack[helpStack.length - 1] === popV[0] && helpStack.length) {
      helpStack.pop();
      popV.shift();
    }
    if (!popV.length) {
      flag = true;
    }
    if (!pushV.length) {
      break;
    }
    helpStack.push(pushV.shift());
  }
  return flag;
}
// 第二种
function IsPopOrder2(pushV, popV) {
  // write code here
  const helpStack = [];
  helpStack.push(pushV.shift());
  while (helpStack.length) {
    const x = helpStack.pop(),
      y = popV.shift();
    if (x !== y) {
      helpStack.push(x);
      popV.unshift(y);
      if (!pushV.length) {
        return false;
      }
      if (pushV.length) {
        helpStack.push(pushV.shift());
      }
    }
  }
  return true;
}

参考文章:
https://www.cnblogs.com/echovic/p/6477897.html
https://www.cnblogs.com/wuguanglin/p/IsPopOrder.html
https://github.com/DavidChen93/-offer-JS-/blob/master/31.1 栈的压入、弹出序列.js

你可能感兴趣的:(Javascript)