一、题目描述
欲知更加详细的题目描述,请看leetcode题目链接
二、分析
- 定义一个栈
stack模拟进栈出栈过程 - 定义一个指针
popedIndex指向poped序列未处理部分 - 遍历入栈序列
pushed,入栈 - 入栈的同时,检查
stack栈顶元素是否等于出栈序列poped未处理部分的头部 - 若相等,
popedIndex指针后移,stack出栈
代码
/**
* @param {number[]} pushed
* @param {number[]} popped
* @return {boolean}
*/
const validateStackSequences = function(pushed, poped) {
// 栈
const stack = []
// 该指针指向poped序列未处理头
let popedIndex = 0
// 遍历pushed序列
for(const item of pushed) {
// 将pushed序列中的元素入栈
stack.push(item)
// 检查poped序列中的元素是否与stack栈的栈顶相等,相等指针后移
while(stack[stack.length - 1] === poped[popedIndex] && stack.length) {
// 处理poped序列的下一项
popedIndex++
// 出栈
stack.pop()
}
}
// 遍历完后,若stack栈内还有元素返回false, 否则返回true
return !stack.length
}