栈的压入、弹出序列

本文介绍了一个算法问题:如何判断一个序列是否为另一个序列的合法弹出顺序。通过使用辅助栈并依次尝试压入和弹出元素的方法来解决这个问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
*/

class Solution {

public:
    // Main Idea:
    // Input vector: 1,2,3,4,5   we try to test 4,5,3,2,1
    // assist statck: we try to push input vector sequentially
    //                1,2,3,4  match 4 pop it 1,2,3 left
    //                we continue push input 5 then 1,2,3,5 match 5 pop it 1,2,3 left
    //                similarly try others 
    //                all matched  return true
    bool IsPopOrder(vector<int> pushV,vector<int> popV) {
  		if(pushV.size() != popV.size() || pushV.size() == 0) return false ;
        
        std::stack<int> st ;// assist stack
        st.push(pushV[0]) ;
        int nPushIndex = 1 ;
        for(std::size_t i = 0; i < popV.size(); ++i) {
            while(!st.empty() && popV[i] != st.top() && nPushIndex < pushV.size()) {// if not match top, only way is try to push more
                st.push(pushV[nPushIndex++]) ;// nPushIndex++
            }
            
            if(st.empty() || popV[i] != st.top()) {// if still not match top, then return false
                                       // if(popV[i] != st.top()) is also okay
                return false ;
            }else {
                st.pop() ;// if matched pop it
            }
        }
        
        return true ;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值