"Sword Finger Offer"-21. Push and pop sequence of the stack

1. Knowledge points of this question

Stack

2. 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)

3. Problem solving ideas

Create a stack and push the array pushA into the stack. When the top element of the stack is equal to the array popA, it will be popped out of the stack. When the loop ends, it is judged whether the stack is empty, and true if it is empty.

4. Code

public class Solution {
    
    
    public boolean IsPopOrder(int[] pushA, int[] popA) {
    
    
        // 创建栈
        Deque<Integer> stack = new LinkedList<>();
        // 遍历数组 pushA,将其压入栈
        for (int i = 0, j = 0; i < pushA.length; i++) {
    
    
            stack.push(pushA[i]);
            // 当栈顶元素等于数组 popA 时,就将其出栈
            while (j < popA.length && stack.peek().equals(popA[j])) {
    
    
                stack.pop();
                j++;
            }
        }
        // 判断栈是否为空,若为空则返回 true
        return stack.isEmpty();
    }
}

Guess you like

Origin blog.csdn.net/bm1998/article/details/113740102