Appearance
剑指Offer 31. 栈的压入、弹出序列
js
/**
* @param {number[]} pushed
* @param {number[]} popped
* @return {boolean}
*/
var validateStackSequences = function(pushed, popped) {
let len = pushed.length
// 如果为空直接返回true
if (len === 0) return true
// 设定一个栈
let stack = []
// 入栈索引
let i = 0
// 出栈索引
let j = 0
// 循环入栈数组
while (i < len) {
// 先入栈
stack.push(pushed[i])
// 如果stack的最后一个元素和popped的第一个元素相等
while(stack[stack.length - 1] === popped[j]) {
// 出栈后移判断下一个
stack.pop()
j++
// 如果出完了说明都可以匹配到
if (j >= popped.length) return true;
}
i++
}
return false
};