• 剑指 Offer 31. 栈的压入、弹出序列


    题目

    剑指 Offer 31. 栈的压入、弹出序列

    我的思路

    基本思路:模拟压栈过程,深搜
    有没有数学上的规律?如果pushed序列中a在b之前,并且popped序列中a比b先弹出,那么a比所有b之后的数字先弹出

    我的实现

    class Solution {
    public:
        
        int lenPushed;
        int lenPopped;
    
        bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
            if(pushed.size()==0)return true;
            int posPushed = 0;
            int posPopped = 0;
            lenPushed = pushed.size();
            lenPopped = popped.size();
            vector<int> stack;
            while(posPushed<=lenPushed){
                if(stack.empty()&&posPushed<lenPushed){
                    stack.push_back(pushed[posPushed]);
                    posPushed++;
                }else{
                    if(stack.empty()&&lenPushed==posPushed)break;
                    if(stack.back()==popped[posPopped]){
                        cout<<stack.back()<<endl;
                        stack.pop_back();
                        posPopped++;
                    }else if(posPushed<lenPushed){
                        stack.push_back(pushed[posPushed]);
                        posPushed++;
                    }else{
                        posPushed++;
                    }
                }
            }
    
            if(stack.empty()&&lenPopped==posPopped)return true;
            else return false;
    
    
        }
    };

    拓展学习

    如果存在重复元素怎么考虑?深搜?

  • 相关阅读:
    深入理解java异常处理机制
    i2c总线
    运行时类型识别(RTTI)
    bcg界面库总结
    c++ 虚函数表
    宽字符,宽字符串
    c++异常处理
    内存管理
    c++中使用联合体
    MFC自定义消息
  • 原文地址:https://www.cnblogs.com/BoysCryToo/p/13474784.html
Copyright © 2020-2023  润新知