[路飞]_leetcode_946.验证栈序列

116 阅读1分钟

给定 pushed 和 popped 两个序列,每个序列中的 值都不重复,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列的结果时,返回 true;否则,返回 false 。

解题思路

我们需要设置一个栈,然后往这个栈添加元素,或删除元素,需要按popped的规则删除。

栈的特性是先进后出,后进先出

  1. 首先先遍历pushed数组,将它的值放入栈 stack 中
  2. 当碰到 index=0 的popped[index]相等时,pop掉这个元素,然后index++
  3. 然后继续查询有没有stack的最后一位与popped[index]相等的值,栈做pop操作。
  |    |
  |  4 |   popped: [4, 5, 3, 2, 1]
  |  3 |          index
  |  2 |
  |  1 |
  |____|
   stack

此时 stack[3] == popped[0] ,所以要stack要pop掉最后一个元素,index++
因为 stack[2] !== popped[1]
然后push新的元素 5 到栈中

  |    |
  |  5 |   popped: [4, 5, 3, 2, 1]
  |  3 |             index
  |  2 |
  |  1 |
  |____|
   stack

此时 stack[3] == popped[1] ,所以stack要pop掉最后一个元素,index++
···

以此类推
最后到pushed便利完位置

代码

var validateStackSequences = function(pushed, popped) {
    let stack = [], index = 0;
    for (let num of pushed) {
        stack.push(num)
        while(stack[stack.length - 1] === popped[index] && stack.length) {
            stack.pop()
            index++
        }
    }
    return !stack.length
};