21、栈的压入、弹出序列

一、题目

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。

二、解法

 1 import java.util.Stack;
 2 public class Solution {
 3     public boolean IsPopOrder(int [] pushA,int [] popA) {
 4            if(pushA.length == 0 || pushA == null 
 5              || popA.length == 0 || popA == null)
 6               return false;
 7           Stack<Integer> temp = new Stack<Integer>();//辅助栈
 8           int index = 0;//popA的下标
 9           for(int i = 0; i < pushA.length; i++){
10               //存入temp中
11               temp.push(pushA[i]);
12               //比较temp的第一个和popA[index]是否相等
13               while(!temp.isEmpty() && temp.peek() == popA[index]){
14                   temp.pop();
15                   index++;
16               }
17           }
18           return temp.isEmpty();
19     }
20 }
原文地址:https://www.cnblogs.com/fankongkong/p/7452175.html