stack push and pop sequence

Question Description
Input two integer sequences, the first sequence represents the stack's push sequence, please check whether the second sequence is 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: the two sequences are of equal length)

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

public class Solution {

    public boolean IsPopOrder(int [] pushA,int [] popA) {
         Stack<Integer> stack = new Stack();
        int j = 0;
        int i = 0; 
        while(j < popA.length){
            int val = popA[j];

            while(stack.isEmpty() || val != stack.peek()){
                 if(i >= pushA.length)
                    return false;
                stack.push(pushA[i++]);               
            }

            stack.pop();
            j++;
        }
       if(stack.isEmpty())
           return true;

       return false;

    }
}

Set up an auxiliary stack, if the stack is empty, push a number in pushA into the stack! If the top element of the stack is different from the total first element of popA, continue to push the element of pushA on the stack until the top element of the stack is the same as the current pointer element of popA, pop the stack, and move the pointer of popA backward;
continue to judge the top element of the stack and the current popA Is the current element of the same, the same, pop the stack; different, continue to push the elements of the pushA stack, until the top element of the stack and the current pointer element of popA are the same, pop the stack, and the popA pointer moves backward;

Guess you like

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