Sword refers to offer to brush questions-GZ21-stack push, pop order

Insert picture description here
Problem-solving ideas:
[Idea] Borrow an auxiliary stack, traverse the stack order, first put the first one on the stack, here is 1, and then judge whether the top element of the stack is the first element in the stack order, here is 4. Obviously 1≠4, so we continue to push the stack until it is equal to start popping. When popping an element from the stack, the stacking sequence will be moved one bit backward until it is not equal, so that the traversal of the stack sequence is completed such as the cycle. If the auxiliary stack is not empty, the pop-up sequence is not the pop-up sequence of the stack.

For example:

Stack 1, 2, 3, 4, 5

Pop 4, 5, 3, 2, 1

First, 1 enter the auxiliary stack, at this time the top of the stack 1≠4, continue to stack 2

At this time, the top of the stack 2≠4, continue to stack 3

At this time, the top of the stack 3≠4, continue to stack 4

At this time, the top of the stack is 4=4, the stack is 4, and the pop sequence is one bit backward, at this time, it is 5, and the auxiliary stack is 1, 2, 3

At this time, the top of the stack 3≠5, continue to stack 5

At this time, the top of the stack is 5=5, the pop-up sequence is 5, and the pop-up sequence is one bit backward, which is 3 at this time, and the auxiliary stack is 1, 2, 3

….

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){
    
    
          return false;
      }
        //辅助栈
        Stack<Integer> s = new Stack();
        //用于标识弹出序列的下标
        int popIndex = 0;
        for(int i = 0; i < pushA.length; i++){
    
    
            s.push(pushA[i]);
            //如果栈不为空,并且栈顶元素等于弹出序列
            while(!s.empty() && s.peek()==popA[popIndex]){
    
    
                //出栈
                s.pop();
                //弹出序列后移一位
                popIndex++;
            }
        }
        //如果辅助栈为空,说明弹出序列是该栈的一个弹出顺序。
        return s.empty();
    }
}

Guess you like

Origin blog.csdn.net/weixin_42118981/article/details/113065605