JZ31. Stack push and pop sequences


1. Description of the topic

Topic link: 31. Stack push and pop sequence

insert image description here

2. Problem-solving ideas

Pushing an element onto the stack refers to putting a new element on top of the top element of the stack to make it a new top element of the stack;

Element popping refers to deleting elements from a stack, also known as making a stack or unstacking. It deletes the top element of the stack and makes its adjacent elements become the new top element of the stack.

As shown in the figure below, given a push sequence pushed and a pop sequence popped, the order (ie permutation) of push/pop operations is uniquely determined.

insert image description here

As shown in the figure below, the data operation of the stack has the characteristics of first-in-last-out, so some pop-up sequences cannot be realized.

insert image description here

So this question considers borrowing an auxiliary stack to simulate the arrangement of push/pop operations. Depending on whether the simulation is successful, the result can be obtained.

  • Push operation: Execute in the order of push sequence.

  • Popping operation: After each push into the stack, loop to judge "栈顶元素 == 弹出序列的当前元素"whether is true, and pop all the top elements of the stack that conform to the order of the popping sequence.

specific methods:

(1) Initialization: Define the auxiliary stack stand pop up the subscript index of the sequencei

(2) Traversing the stack push sequence, pushing elements into the stack: cyclic popping: if stthe top element of the stack == the popping sequence element popped[i], execute popping, and theni++

(3) Return value: If stis empty, the popup sequence is valid.

3. Animation presentation

Let's see a animation

insert image description here

4. Code implementation

code example

class Solution {
    
    
public:
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
    
    
        // 入栈和出栈的元素个数必须相同
        if (pushed.size() != popped.size())
            return false;

        stack<int> st;
        int i = 0;
        for (auto e : pushed) {
    
    
            st.push(e);
            while (!st.empty() && st.top() == popped[i]) {
    
    
                ++i;
                st.pop();
            }
        }
        // 如果栈不为空,说明不匹配
        return st.empty();
    }
};

Guess you like

Origin blog.csdn.net/m0_63325890/article/details/128372776