[剑指offer 编程题]栈的压入、弹出序列

class Solution {
public:
    bool IsPopOrder(vector<int> pushV,vector<int> popV) {
        int i=0,j=1;
        int length = pushV.size();
        vector<int> testV;

        testV.push_back(pushV[0]);

        while(testV.back() != popV[0] && j < length){
            testV.push_back(pushV[j]);      
            j++;
        }//为了开头,首先压入这么多


        while(length-- > 0){//验算几次
            if(popV[i] == testV.back()){
                i++;
                testV.pop_back();//如果相同就出栈
            }else{//栈顶不是所要的数字
                //尝试着继续压栈 
                while(j < pushV.size() && testV.back()!= popV[i]){//要么压完所有栈出来,要么压到对的那一栈出来
                    testV.push_back(pushV[j]);
                    j++;
                }

                if(popV[i] == testV.back()){
                    i++;
                    testV.pop_back();//如果相同就出栈
                }else{
                    //压完所有栈都没看见,那肯定是在栈中,则失败。
                    return false;
                }                              
            }
        }

        return true;
        }
};
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务