⚡️Algorithm exercise~stack-stack push and pop sequence~⚡️

topic description

Input two integer sequences, the first sequence represents the push order of the stack, please judge whether the second sequence may be the pop order of the stack. Assume that all numbers pushed onto the stack are unequal. For example, the sequence 1, 2, 3, 4, 5 is the push sequence of a certain stack, and 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 the two sequences are equal)

problem solving ideas

Using a stack to make
a stack is characterized by a first-in last-out list. A stack is a special linear list that can only be inserted and deleted at one end. It stores data according to the principle of first-in-last-out. The data that enters first is pushed to the bottom of the stack, and the last data is on the top of the stack. When data needs to be read, data is popped from the top of the stack.
Push the array A into the stack, when the top element of the stack is equal to the array B, pop it out of the stack, when the loop ends, judge whether the stack is empty, if it is empty, return true
.

code example


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

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

Topic link:
JZ21 stack push, pop sequence

Guess you like

Origin blog.csdn.net/weixin_43863054/article/details/120361056