Offer the twenty-first to prove safety issues stack push, pop sequence

Two input sequence of integers, the first sequence representing a pressed stack order, determines whether it is possible for the second sequence the order of the pop-up stack. All figures are not pushed onto the stack is assumed equal. Such as a sequence of a sequence of 1,2,3,4,5 is pressed into the stack, the push sequence is 4,5,3,2,1 sequence corresponding to a sequence of pop, but 4,3,5,1,2 it is impossible to push pop-up sequence of the sequence. (Note: the length of the two sequences are equal)

Thinking: push fixed number of operations, with a variable number of push recording, while when the top of the stack pointer and the position of the pop-up sequence is the same, performing the push operation.

Code is implemented as follows:

 1 import java.util.*;
 2 
 3 public class Solution {
 4     public boolean IsPopOrder(int [] pushA,int [] popA) {
 5         Stack s = new Stack();
 6         s.push(pushA[0]);
 7         int count = 0;
 8         int a=1,b=0;
 9         while(count<pushA.length+1&&b<popA.length){
10             if(s.peek().equals(popA[b])){
11                 s.pop();
12                 b++;
13             }else{
14                 if(a<pushA.length){
15                     s.push(pushA[a]);
16                     a++;
17                     count++;
18                 }else{
19                     count++;
20                 }
21             }
22         }
23         if(s.isEmpty())
24             return true;
25         else
26             return false;
27     }
28 }

(Ps: will be issued over the stack when empty stack execution method peek .... think before abnormal returns null object)

Guess you like

Origin www.cnblogs.com/haq123/p/12185424.html