劍指offer之面試題22:棧的壓入、彈出序列

題目:輸入兩個整數序列,第一個序列表示棧的壓入順序,請判斷第二個序列是否爲該棧的彈出順序。假設壓入棧的全部數字均不相等。例如序列1,2,3,4,5是某棧的壓入順序,序列4,5,3,2,1是該壓棧序列對應的一個彈出序列,但4,3,5,1,2就不多是該壓棧序列的彈出序列。(注意:這兩個序列的長度是相等的)ide

思路1:spa

wKiom1eHXfCAIHbQAATe4DiUJ84159.png

代碼:blog

class Solution {
public:
    bool IsPopOrder(vector<int> pushV,vector<int> popV) 
    {
        if(pushV.size()!=popV.size())
        {
            return false;
        }
        stack<int> ret;
        int j=0;
        for(int i=0;i<pushV.size();i++)
        {
            if(pushV[i]!=popV[j])
            {
                ret.push(pushV[i]);
            }
            else
            {
                j++;
            }
        }
        while(!ret.empty())
        {
            int top=ret.top();
            ret.pop();
            if(popV[j]!=top)
            {
                return false;
            }
            else
            {
                j++;
            }
            
        }
        return true;
    }
};

將思想精簡,代碼精簡後get

class Solution {
public:
    bool IsPopOrder(vector<int> pushV,vector<int> popV) 
    {
     	if(pushV.size()!=popV.size())
        {
            return false;
        }
        stack<int> s1;
        for(int i=0,j=0;i<pushV.size();i++)
        {
            s1.push(pushV[i]);
            while(j<popV.size()&&s1.top()==popV[j])
            {
                j++;
                s1.pop();
            }
        }
        return s1.empty();
    }
};
相關文章
相關標籤/搜索