Sword refers to Offer 31. Stack push and pop sequence (C++) simulation

Enter two integer sequences. The first sequence represents the order in which the stack is pushed. Please judge whether the second sequence is the pop-up order of the stack. Assume that all numbers pushed onto the stack are not equal. For example, the sequence {1,2,3,4,5} is the push sequence of a certain stack, the sequence {4,5,3,2,1} is a pop sequence corresponding to the push sequence, but {4,3 ,5,1,2} cannot be the pop sequence of the stack sequence.

Example 1:

输入:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
输出:true
解释:我们可以按以下顺序执行:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

Example 2:

输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
输出:false
解释:1 不能在 2 之前弹出。

prompt:

0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] <1000
pushed is the arrangement of popped.
Note: This question is the same as the main site question 946: https://leetcode-cn.com/problems/validate-stack-sequences/

Problem-solving ideas:

As shown below, a given sequence into press-pop sequence pushed and popped, the push / pop operation order (i.e., arrangement) is uniquely determined to.
Insert picture description here
As shown below, the data operation has a stack after first-out characteristics, so some pop-up sequence can not be achieved.
Insert picture description here
Insert picture description here
Insert picture description here

The title pointed out that pushed is the arrangement of popped. Therefore, there is no need to consider situations where pushed and popped have different lengths or contain different elements.

class Solution {
    
    
public:
    // 建立辅助栈,按照入栈出栈顺序模拟一次,若最后辅助栈为空则返回true
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
    
    
        // 辅助栈
        stack<int> stk;
        int i = 0;
        for (int p : pushed) {
    
    
            // 按照pushed的顺序以此入栈
            stk.push(p);
            // 如果辅助栈不为空,且辅助栈的栈顶元素等于出栈的元素,则出栈,出栈序号加1
            while (!stk.empty() && stk.top() == popped[i]) {
    
    
                stk.pop();
                i ++;
            }
        }
        return stk.empty();
    }
};

Complexity analysis:

Time complexity O(N): where N is the length of the list pushed; each element is pushed and popped at most once, that is, a total of 2N push and pop operations are at most.
Space complexity O(N): The auxiliary stack stack can store up to N elements at the same time.

Author: jyd
link: https: //leetcode-cn.com/problems/zhan-de-ya-ru-dan-chu-xu-lie-lcof/solution/mian-shi-ti-31-zhan-de-ya -ru-dan-chu-xu-lie-mo-n-2/
Source: LeetCode (LeetCode)
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/qq_30457077/article/details/114988115