[The sword refers to the offer brushing the question] AcWing 42. The push and pop sequence of the stack (stack, simulation)

ideas

To judge whether the input sequence and output sequence of the stack match, it only needs to be divided into the following steps:

  1. Determine whether the current top element of the stack is the same as the next stack to be output;
  2. If it is the same, it must pop up;
  3. If not, the next element must be pushed onto the stack

topic

Input two integer sequences, the first sequence represents the stack's push sequence, please judge whether the second sequence may be the stack's pop-up sequence.

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 stack, the sequence 4, 5, 3, 2, 1 is a pop sequence corresponding to the stack sequence, but 4, 3, 5, 1, 2

It cannot be the pop sequence of the push sequence.

Note: If the lengths of the two sequences are not equal, it is regarded as not a stack push or pop sequence. If both sequences are empty, it is regarded as a stack push and pop sequence.
data range

sequence length [0,1000]

.
Sample

Input: [1,2,3,4,5]
[4,5,3,2,1]

output: true

java code

class Solution {
    
    
    
    /**
     * 判断栈的输入序列核输出序列是否匹配,分为以下几步:
     * 1. 判断当前栈顶元素和下一个要输出的栈是否一样的
     *      如果是,必然弹出;如果不是,必然将下一个元素入栈
     */
    
    public boolean isPopOrder(int [] pushV,int [] popV) {
    
    
        
        if (pushV.length != popV.length)
            return false;
        
        if (pushV.length == 0 && popV.length == 0)
            return true;
        
        Stack<Integer> stk = new Stack<Integer>();
        
        int i = 0;
        for (int x : pushV)
        {
    
    
            stk.push(x);
            while ( !stk.empty() && stk.peek() == popV[i] )
            {
    
    
                stk.pop();
                i++;
            }
        }
        
        if (stk.empty())
            return true;
        return false;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326234432&siteId=291194637