1. 程式人生 > >劍指offer--棧的壓入、彈出序列

劍指offer--棧的壓入、彈出序列

題目描述
輸入兩個整數序列,第一個序列表示棧的壓入順序,請判斷第二個序列是否可能為該棧的彈出順序。假設壓入棧的所有數字均不相等。例如序列1,2,3,4,5是某棧的壓入順序,序列4,5,3,2,1是該壓棧序列對應的一個彈出序列,但4,3,5,1,2就不可能是該壓棧序列的彈出序列。(注意:這兩個序列的長度是相等的)
程式碼實現(JAVA)

import java.util.ArrayList;
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>    stack=new Stack<Integer>();
        int popIndex=0;
        for(int i=0;i<pushA.length;i++){
            stack.push(pushA[i]);
            while(!stack.empty()&&stack.peek()==popA[popIndex])
            {
                stack.pop();
                popIndex++;
            }
        }
        return stack.empty();
    }
}