Source: Niu ke net "jian refers to offer"
The title description input two integer sequence, the first sequence represents the stack's indentation order, determine whether the second sequence is the pop-up order of the stack. Assume that all the numbers that are pressed into the stack are not equal. For example, the sequence 1,2,3,4,5 is the indentation order of a 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 is not likely to be the pop-up sequence of the stack sequence. (Note: The lengths of the two sequences are equal)
pusha={1,2,3,4,5}
popa={4,5,3,1,2}
popb={4,3,5,1,2}
First look at Popa, the first is 4, so you need to 1,2,3,4 all into the stack, and then pop up 4, at this time top=3. The next one is 5, not the top, so you need to put the next element in the Pusha into the stack, and then compare whether the new is equal to 5. If it is equal, the stack will be out, and if not, continue to stack the numbers from Pusha. The termination condition is that the stack is empty or the Pusha array traversal is complete.
1 Public BooleanIspoporder (int[] Pusha,int[] PopA) {2 if(pusha.length==0 | | popa.length==0)return false;3 if(pusha.length!=popa.length)return false;4 5stack<integer> stack =NewStack<integer>();6Stack.push (Pusha[0]);//autoboxing7 8 for(intI=1, j=0; ;){9 if(Stack.empty ())return true;Ten if(!stack.empty () && Stack.peek ()!=popa[j]) {//Unboxing One if(i==pusha.length) Break; A Stack.push (Pusha[i]); -i++; -}Else if(!stack.empty () && stack.peek () = =Popa[j]) { the Stack.pop (); -J + +; - } - } + - return false; +}
Stack push-in, pop-up sequence