Title Description
Enter two sequences of integers , The first sequence represents the push order of the stack , Please determine if the second sequence is likely to be the pop-up sequence of the stack . Suppose that all the Numbers pushed are not equal . For example, the sequence 1,2,3,4,5 Is the push order of a stack , Sequence 4,5,3,2,1 Is a popup sequence corresponding to the stack sequence , but 4,3,5,1,2 It cannot be a popup sequence of the push sequence .( Be careful : The lengths of the two sequences are equal )
Their thinking
/*
* The implementation idea is as follows :
* 1、 Define a stack , To test it ;
* 2、 Put the stack one by one on the stack sequence , In the process of entering the stack, it is compared with the stack out sequence ;
* 3、 If equal , Out of the stack ; The out of stack sequence pointer moves backward . If the range , Continue to the first 2 Step ;
* 4、 Until the stack sequence traversal is completed .
* For the return value , If it's not a stack sequence , Then the stack will not be empty ; Only when it's right , The stack will be empty .
*/
Concrete realization
public static boolean isPopOrder(int [] pushA,int [] popA) {
Stack<Integer> assistant = new Stack<>();
int index = 0;
for(int i = 0; i < pushA.length; i++) {
assistant.push(pushA[i]);
while(!assistant.isEmpty() && assistant.peek() == popA[index]){
assistant.pop();
index++;
}
}
return assistant.isEmpty();
}
Thank you for your !