题解 | #栈的压入、弹出序列#
栈的压入、弹出序列
https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106
/** * 核心思想:辅助栈记录push,每次push与pop顺序判断,相等则pop,如果不想等则顺序不对,结束调用 * 1. 定义辅助栈 * 2. 遍历出栈顺序,其中判断辅助栈top元素不等于出栈顺序,则可一直入栈 * 3. 当等于出栈顺序,则辅助栈pop * 4. 不等于出栈顺序,则表示压入弹出序列不匹配,结束调用 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * @param pushV int整型一维数组 * @param popV int整型一维数组 * @return bool布尔型 */ function IsPopOrder( pushV , popV ) { // write code here const n = pushV.length const s = [] let j = 0; for(let i=0;i<n;i++){ while(j < n && (!s.length || s[s.length - 1] !== popV[i])){ s.push(pushV[j]) j++ } if(s[s.length-1] === popV[i]){ s.pop() }else{ return false } } return true } module.exports = { IsPopOrder : IsPopOrder };