# 946. 验证栈序列

# 解题思路

var validateStackSequences = function (pushed, popped) {
  const stack = []
  const len = pushed.length
  let j = 0

  for (let i = 0; i < len; i++) {
    const cur = pushed[i]
    const poppedCur = popped[j]

    if (cur === poppedCur) {
      j++
      // 同时往前找
      while (stack.length && stack[stack.length - 1] === popped[j]) {
        j++
        stack.pop()
      }
    } else {
      stack.push(cur)
    }
  }

  return return stack.length === 0
}

查看官方题解,请点击前往查看 (opens new window)

# 参考