Push and pop of JZ21 stack

Title Description
Input two sequences of integers, the first sequence indicates the push order of the stack, please judge whether the second sequence may be the pop order of the stack. Assume that all numbers pushed onto the stack are unequal. For example, the sequence 1, 2, 3, 4, 5 is the push sequence of a certain stack, and the sequence 4, 5, 3, 2, 1 is a pop sequence corresponding to the push sequence, but 4, 3, 5, 1, 2 It cannot be the pop sequence of the push sequence. (Note: the lengths of the two sequences are equal)

Solution:
push = {1,2,3,4,5}; pop = {4,5,3,2,1}
(1) With the aid of the auxiliary stack st, 1,2,3 are not equal to the top element 4 in turn Push st into the stack, st = {1,2,3}
(2) 4 = 4 (the top element of the stack), pop 4 out of the stack, pop moves backward one bit, pointing to 5 (
3) 3 in st is not equal to 5, at this time Push 5, st = {1,2,3,5}
(4) 5 = 5 (the top element of the stack), pop 5, pop move one bit backward, st pop 5
(5) and so on, pop the stack 3, 2, 1, st is finally empty, and pop is the pop-up sequence of push; otherwise, it is not the pop-up sequence of push. The
specific program is implemented as follows:

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

Guess you like

Origin blog.csdn.net/pikaqiu_n95/article/details/109588693