[Daily question] 28: Stack push and pop sequence

Title description

Enter two integer sequences. The first sequence indicates the stacking sequence. Please determine whether the second sequence may be the popping sequence of the stack. Assume that all numbers pushed onto the stack are not equal.

Examples:

Sequence 1,2,3,4,5 is the push sequence of a stack, sequence 4,5,3,2,1 is a pop-up sequence corresponding to the stack sequence, but 4,3,5,1,2 is It cannot be the pop sequence of the push sequence. (Note: The lengths of the two sequences are equal)

Answer code:

class Solution {
public:
    bool IsPopOrder(vector<int> pushV,vector<int> popV) {
        stack<int> tmp;
        int i = 0;
        
        for(auto & vi : pushV){
            tmp.push(vi);
            
            for(; !tmp.empty() && tmp.top() == popV[i]; ++i){
                tmp.pop();
            }
        }
        return tmp.empty();
    }
};

If you have other different opinions, please leave a message to discuss ~~~

Published 152 original articles · praised 45 · 10,000+ views

Guess you like

Origin blog.csdn.net/AngelDg/article/details/105378423