棧的壓入彈出序列問題

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdlib.h>
#include<iostream>
using namespace std;

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

/*
解題思路:
利用一個棧,將pushV中的元素依次插入,若棧頂元素和popV中pos元素相等則pop棧頂元素並讓pos指向下一個元素
pushV中元素插入結束若棧爲空則說明知足條件,不然不知足。
*/
class Solution 
{
public:
    bool IsPopOrder(vector<int> pushV, vector<int> popV) {
        stack<int> s;
        if (pushV.size() != popV.size())
        {
            return false;
        }
        int i = 0;
        int j = 0;
        while (i < pushV.size())
        {
            s.push(pushV[i++]);
            while (!s.empty() && s.top() == popV[j])
            {   
                    s.pop();
                    j++;
            }
        }
        if (s.empty())
        {
            return true;
        }
        else
        {
            return false;
        }

    }
};
int main()
{
    vector<int>v1{1, 2, 3, 4, 5};
    vector<int>v2{ 4,5,3,2,1};
    Solution s;
    int a=s.IsPopOrder(v1, v2);
    cout << a << endl;
    system("pause");
    return 0;
}
相關文章
相關標籤/搜索