[Offer] [31] [stack push, pop sequence]

Title Description

  Two input sequence of integers, the first sequence representing a stack pressed into order , please determined second sequence whether for the stack of pop-up sequence . All figures are not pushed onto the stack is assumed equal. For example, the sequence {1,2,3,4,5} is a stack push sequence, the sequence {4,5,3,2,1} is a pop-up sequence of the sequence corresponding to the push, but the {4,3 , 5,1,2} would not pop-up sequence is the push sequence.

Cattle brush off questions address network

Ideas analysis

  1. If the next number is just the top of the stack pop number, then pop up directly;
  2. If the next pop-up numbers are out of the stack, put the push sequence numbers have not pushed onto the stack of the auxiliary stack until the next pop required number pressed into the far top of the stack; still if all the numbers are pushed onto the stack did not find the next pop-up number, then the sequence can not be a pop-up sequence .

Test Case

  1. Functional test: two input array comprising a plurality of digital or digital only; a second array is pressed into the pop-up sequence corresponding to a sequence or not the first stack of array representation.
  2. Special Test Input: Input nullptr two pointers.

Java code

public class Offer31 {
    public static void main(String[] args) {
        test1();
        test2();
        test3();

    }

    public static boolean IsPopOrder(int[] pushA, int[] popA) {
        return Solution1(pushA,popA);
    }

    private  static boolean Solution1(int[] pushA, int[] popA) {
        if(pushA==null || popA==null){
              return false;
            }
            if(pushA.length!=popA.length || pushA.length==0){
              return false;
            }
            Stack<Integer> stack = new Stack<Integer>();
            int popIndex  = 0;
            for(int pushIndex=0;pushIndex<pushA.length;pushIndex++){
                stack.push(pushA[pushIndex]);
                while(!stack.empty()&&stack.peek()==popA[popIndex]){
                    stack.pop();
                    popIndex++;
                }
            }
            return stack.empty();
    }

    private static void test1() {

    }

    private static void test2() {

    }

    private static void test3() {

    }
}

Code link

Offer to prove safety codes -Java

Guess you like

Origin www.cnblogs.com/haoworld/p/offer31-zhan-de-ya-ru-dan-chu-xu-lie.html