• 剑指offer--面试题22


    关键在于思路,  需要两个输入向量,而函数中需要一个辅助栈

                    思路:以待判出栈序列为基础,逐个判断它与栈顶元素是否相等,相等则弹出且j++,这表明此元素可为出栈顺序元素,不相等则栈元素不断入栈,直至相等,否则则判为非出栈序列!

    #include<stack>
    
    bool IsStackSquence(int* array1, int length1, int* array2, int length2)
    {
        bool IsOutStack = true;
        if(array1 == NULL || length1 <= 0 || array2 == NULL || length2 <= 0 || length1 != length2)
            return !IsOutStack;
    
        std::stack<int> st;    
        int i = 0;
        int j = 0;
    
        st.push(array1[i++]);
    
        while(j < length2)
        {
            while(array2[j] != st.top() && i < length1)
            {
                st.push(array1[i]);
                i++;
            }
            if(array2[j] != st.top() && i == length1)
                return !IsOutStack;
    
            st.pop();
            j++;
        }
    
        return IsOutStack;
    }

     参考代码:

    #include <stack>
    
    bool IsPopOrder(const int* pPush, const int* pPop, int nLength)
    {
        bool bPossible = false;
    
        if(pPush != NULL && pPop != NULL && nLength > 0)
        {
            const int* pNextPush = pPush;
            const int* pNextPop = pPop;
    
            std::stack<int> stackData;
    
            while(pNextPop - pPop < nLength)
            {
                // 当辅助栈的栈顶元素不是要弹出的元素
                // 先压入一些数字入栈
                while(stackData.empty() || stackData.top() != *pNextPop)
                {
                    // 如果所有数字都压入辅助栈了,退出循环
                    if(pNextPush - pPush == nLength)
                        break;
    
                    stackData.push(*pNextPush);
    
                    pNextPush ++;
                }
    
                if(stackData.top() != *pNextPop)
                    break;
    
                stackData.pop();
                pNextPop ++;
            }
    
            if(stackData.empty() && pNextPop - pPop == nLength)
                bPossible = true;
        }
    
        return bPossible;
    }

    学习:const int*

    清醒时做事,糊涂时读书,大怒时睡觉,独处时思考; 做一个幸福的人,读书,旅行,努力工作,关心身体和心情,成为最好的自己 -- 共勉
  • 相关阅读:
    Java——读取和写入txt文件
    Java——去除字符串中的中文
    web.xml——Error:cvc-complex-type.2.4.a: Invalid content was found starting with element
    poi--读取不同类型的excel表格
    poi——读取excel数据
    java静态代码块
    Java-main方法中调用非static方法
    dom4j--解析xml文件
    python发送邮件
    JWT认证原理及使用
  • 原文地址:https://www.cnblogs.com/hello-yz/p/3271722.html
Copyright © 2020-2023  润新知