题解 | #栈的压入、弹出序列#
栈的压入、弹出序列
https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106
function IsPopOrder(pushV, popV) {
//创建一个模拟栈
let stack = [];
//遍历入栈数组
for (let i = 0; i < pushV.length; i++) {
//压入模拟栈中
stack.push(pushV[i]);
//当模拟栈非空时
while (stack.length > 0) {
//如果栈顶元素和弹出元素匹配
if (stack[stack.length - 1] == popV[0]) {
//弹出栈顶元素
stack.pop();
//由于popV前面的已经没用了,直接移除
popV.shift();
} else {
//如果不匹配,跳出while循环,继续压入下一个入栈元素
break;
}
}
}
//若模拟栈空,则匹配成功
return stack.length === 0;
}
module.exports = {
IsPopOrder: IsPopOrder,
};
module.exports = {
IsPopOrder: IsPopOrder,
};
#栈##算法##数据结构##模拟栈#
美的集团公司福利 753人发布