这个题的意思是给定两个序列,判断一个序列是否是另一个序列的压栈的弹出序列。那么这个题的思想就是以弹出序列的顺序进行往后查找,如果当前压入栈的棧顶元素并不等于当前弹出值,就把压入栈的序列中后序的数值不断的压入栈,直到相等,然后移动弹出栈的指针以及从栈中弹出当前的压入值,如此循环往复。如果到最后压入栈的序列已经遍历到头了,但是仍然没有与弹出栈相等的值,就不是对应序列。如果栈和弹出序列均只剩一个数值了,且相等,那么就是对应序列。具体代码如下:
1 import java.util.*; 2 public class ThePopSeq{ 3 4 public boolean isRight(int [] pushs, int [] pops){ 5 boolean result = false; 6 ArrayList<Integer> pushSeq = new ArrayList<Integer>(); 7 int popIndex = 0,pushIndex= 1; 8 if(pushs.length==0&&pops.length==0){ 9 return true; 10 } 11 if(pushs.length!=pops.length){ 12 return result; 13 } 14 pushSeq.add(pushs[0]); 15 while(true){ 16 if(pops[popIndex]!=pushSeq.get(pushSeq.size()-1) && pushIndex<pushs.length){ 17 pushSeq.add(pushs[pushIndex]); 18 pushIndex++; 19 } 20 if(pops[popIndex]!=pushSeq.get(pushSeq.size()-1) && pushIndex==pushs.length){ 21 break; 22 } 23 if(pops[popIndex]==pushSeq.get(pushSeq.size()-1)){ 24 if(popIndex==pops.length-1&&pushSeq.size()==1){ 25 result = true; 26 break; 27 }else{ 28 popIndex++; 29 pushSeq.remove(pushSeq.size()-1); 30 } 31 } 32 } 33 return result; 34 } 35 36 public static void main(String [] args){ 37 int [] pushs = {1,2,3,4,5}; 38 int [] pops = {4,5,3,1,2}; 39 ThePopSeq tps = new ThePopSeq(); 40 System.out.println(tps.isRight(pushs,pops)); 41 } 42 43 }