题解 | #栈的压入、弹出序列#

栈的压入、弹出序列

http://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106

function IsPopOrder(pushV, popV) {
  if (!pushV || !popV || pushV.length !== popV.length) {
    return;
  }
  const stack = new Stack();
  let j = 0;
  for (let i = 0; i < pushV.length; i++) {
    stack.push(pushV[i]); //遍历push栈
    while (!stack.isEmpty() && stack.peek() == popV[j]) {
      stack.pop(); //相等则将stack辅助栈栈顶弹出,并将pop栈的index移动
      j++;
    }
  }
  return stack.isEmpty();
}
class Stack {
  constructor() {
    this.arr = [];
  }
  push(item) {
    this.arr.push(item);
  }
  pop() {
    this.arr.pop();
  }
  isEmpty() {
    return this.arr.length === 0;
  }
  peek() {
    return this.arr[this.arr.length - 1];
  }
}
module.exports = {
  IsPopOrder: IsPopOrder,
};

全部评论

相关推荐

JamesGosling1:同一个公司的实习为什么写三次,就算是不同的小组的话,直接写一段要好点吧
点赞 评论 收藏
分享
野猪不是猪🐗:现在的环境就是这样,供远大于求。 以前卡学历,现在最高学历不够卡了,还要卡第一学历。 还是不够筛,于是还要求得有实习、不能有gap等等... 可能这个岗位总共就一个hc,筛到最后还是有十几个人满足这些要求。他们都非常优秀,各方面都很棒。 那没办法了,看那个顺眼选哪个呗。 很残酷,也很现实
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务