Prove safety Offer: stack push, pop sequence (java version)

Title Description

Two input sequence of integers, the first sequence representing a pressed stack order, determines whether it is possible for the second sequence the order of the pop-up stack.
All figures are not pushed onto the stack is assumed equal. Such as a sequence of a sequence of 1,2,3,4,5 is pressed into the stack, the push sequence is 4,5,3,2,1 sequence corresponding to a sequence of pop, but 4,3,5,1,2 it is impossible to push pop-up sequence of the sequence. (Note: the length of the two sequences are equal)

analysis

Borrow an auxiliary stack, push traversal order, the first placed on the stack first, here 1, is determined and then the top element is not out of the first element stack order, this is 4, it is clear that a ≠ 4 so we continue to push until after the start of an equal stack, the stack is an element, it will move back one, until the order is not equal to the stack,
so that circulation Yazhan order traversal is complete, if the auxiliary stack is not empty described sequence is not the sequence of pop pop stack.

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

Guess you like

Origin blog.csdn.net/qq_43165002/article/details/93716601