Niu Ke (21) push and pop sequence of stack

//     Title description
 //     Enter two integer sequences, the first sequence represents the stack's push sequence, please judge 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 certain stack, and the sequence 4, 5, 3, 2, 1 is a pop-up sequence corresponding to the stack sequence,
 //     but 4, 3, 5 ,1,2 cannot be the pop-up sequence of the push sequence. (Note: the two sequences are of equal length)

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

 

Guess you like

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