Push and pop the stack sequence to prove safety offer-

Title Description

Two input sequence of integers, the first sequence representing a pressed stack order, determines whether it is possible for the second sequence the order of the pop-up stack. All figures are not pushed onto the stack is assumed equal. Such as a sequence of a sequence of 1,2,3,4,5 is pressed into the stack, the push sequence is 4,5,3,2,1 sequence corresponding to a sequence of pop, but 4,3,5,1,2 it is impossible to push pop-up sequence of the sequence. (Note: the length of the two sequences are equal)

Thinking

  • Note that the stack is pressed into the order is not always directly pressed, the eject operation mingled
  • Using an auxiliary stack, press fitting is pressed into a sequence, each stack is determined if the auxiliary element is equal to the value of the stack pop sequence, we put the top of the stack pop, pop then forward pointer sequence. If all the elements of the sequence pushed onto the stack can not find a value in the pop-up pop-up sequence, then return false friends.

AC Code

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

class Solution
{
public:
    bool IsPopOrder(vector<int> pushV, vector<int> popV)
    {
        stack<int> s;
        int index = 0;
        for (int i = 0; i < pushV.size(); i++)
        {
            s.push(pushV[i]);
            if (s.top() == popV[index])
            {
                s.pop();
                index++;
            }
        }  
        while (!s.empty()) //所有的元素压入完成,判断能否弹出
        {
            if (s.top() == popV[index])
            {
                s.pop();
                index++;
            }
            else
                return false;
        }
        return true;
    }
};
int main()
{
    vector<int> pushv = {1, 2, 3, 4};
    vector<int> popv = {4, 3, 2, 1};
    Solution so;
    cout << so.IsPopOrder(pushv, popv);

    return 0;
}
Published 58 original articles · won praise 7 · views 2700

Guess you like

Origin blog.csdn.net/weixin_42100456/article/details/104118312