Pressed stack to prove safety offer, the pop-up sequence (using an auxiliary stack)

Ideas:

Borrow an auxiliary stack, push traversal order, into a first talk about the stack, 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, and so the cycle Yazhan order traversal is complete, if the auxiliary stack is not empty described sequence is not the sequence of pop pop stack.

 

For example:

Drawing 1,2,3,4,5

Stack 4,5,3,2,1

1 into the first auxiliary stack, when the stack 1 ≠ 4, continued stack 2

At this time, the stack 2 ≠ 4, continue to stack 3

At this time, the stack 3 ≠ 4, 4 continue to stack

At this time, the stack 4 = 4, the stack 4, a pop-up sequence back, in this case the auxiliary stack 5 inside 1,2,3 ,,

At this time, the stack 3 ≠ 5, 5 continue to push

5 = At ​​this point the stack 5, the stack 5, a pop-up sequence back, in this case the auxiliary stack 3 which is 2,3 ,,

….

Followed by the implementation, and finally the auxiliary stack is empty. If not empty pop-described sequence is not the sequence of pop stack.
 
Code:
import java.util.Stack;
public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
      if(pushA.length == 0 || popA.length == 0){
          return false;
      }
      Stack<Integer> s = new Stack<Integer>();
      int popIndex = 0;
      for(int i = 0;i < pushA.length;i++){
          s.push(pushA[i]);
          while(!s.empty() && s.peek() == popA[popIndex]){
              s.pop();
              popIndex++;
          }
      }
      return s.empty();
   }
}

  

Guess you like

Origin www.cnblogs.com/maohaitao/p/11407155.html