Implemented in Java: Input 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.

Title description

Enter two integer sequences. The first sequence indicates the order in which the stack is pushed. Please judge whether the second sequence may be the pop 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 order 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 It cannot be the pop sequence of the push sequence. (Note: the lengths of these two sequences are equal)

Ideas

Create a new stack and push array A into the stack. When the top element of the stack is equal to array B, it will be popped out of the stack. When the loop ends, it is judged whether the stack is empty. If it is empty, it returns true.

Code

import java.util.ArrayList;
import java.util.Stack;

public class Solution {
    
    
    public boolean IsPopOrder(int [] pushA,int [] popA) {
    
    
        if (pushA.length == 0 || popA.length == 0 || popA.length != pushA.length) {
    
    
            return false;
        }
        Stack<Integer> stack = new Stack<>();
        int j = 0;
        for (int i=0;i<pushA.length;i++) {
    
    
            stack.push(pushA[i]);
            
            while (!stack.isEmpty() && stack.peek() == popA[j]){
    
    
                stack.pop();
                j++;
            }
        }
        return stack.isEmpty();
    }
}

Guess you like

Origin blog.csdn.net/weixin_44285445/article/details/108573123