题解 | #栈的压入、弹出序列#

栈的压入、弹出序列

https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106

解法一:笨方法(列出所有情况)

function IsPopOrder(pushV, popV)
{
    // write code here
    const stack = []
    while (popV.length > 0) {
        const currentPop = popV.shift()
        if (pushV.length > 0 && stack.length === 0) {
            if (pushV[0] === currentPop) {
                pushV.shift()
            } else {
                while (pushV.length > 0 && pushV[0] !== currentPop) {
                    const currentPush =  pushV.shift()
                    stack.push(currentPush)
                }
                if (pushV.length === 0) {
                    return false
                } else {
                    pushV.shift()
                }
            }
        } else if (pushV.length > 0 && stack.length > 0) {
            if (pushV[0] === currentPop) {
                pushV.shift()
            } else if (stack[stack.length - 1] === currentPop) {
                stack.pop()
            } else {
                while (pushV.length > 0 && pushV[0] !== currentPop) {
                    const currentPush =  pushV.shift()
                    stack.push(currentPush)
                }
                if (pushV.length === 0) {
                    return false
                } else {
                    pushV.shift()
                }
            }
        } else if (pushV.length === 0 && stack.length > 0) {
            if (stack[stack.length - 1] === currentPop) {
                stack.pop()
            } else {
                return false
            }
        } else {
            return false
        }
    }
    return true
}
module.exports = {
    IsPopOrder : IsPopOrder
};

解法二:

function IsPopOrder(pushV, popV)
{
    // write code here
    const stack = []
    let j = 0
    for (let i = 0; i < popV.length; i++) {
        while (j < pushV.length && (stack.length === 0 || stack[stack.length - 1] !== popV[i])) {
            stack.push(pushV[j])
            j++
        }

        if (stack[stack.length - 1] === popV[i]) {
            stack.pop()
        } else {
            return false
        }
    }
    return true
}
module.exports = {
    IsPopOrder : IsPopOrder
};



全部评论

相关推荐

死在JAVA的王小美:哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈,我也是,让我免了一轮,但是硬气拒绝了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务