輸入兩個整數序列,第一個序列表示棧的壓入順序,請判斷第二個序列是否爲該棧的彈出順序。
假設壓入棧的所有數字均不相等。例如序列1,2,3,4,5是某棧的壓入順序,序列4,5,3,2,1是該壓棧序列對應的一個彈出序列,但4,3,5,1,2就不可能是該壓棧序列的彈出序列。(注意:這兩個序列的長度是相等的)
import java.util.*;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0, j = 0; i < popA.length; i++) {
//如果和棧頂相同
if (!stack.isEmpty() && popA[i] == stack.peek()) {
stack.pop();
continue;
}
//往後走,將不一樣的塞進棧
for (; j < pushA.length; j++) {
if (popA[i] == pushA[j]){ break; }
else stack.push(pushA[j]);
}
if (j == pushA.length) return false;
else j++;
}
return true;
}
}