題目描述
輸入兩個整數序列,第一個序列表示棧的壓入順序,請判斷第二個序列是否可能爲該棧的彈出順序。假設壓入棧的所有數字均不相等。例如序列1,2,3,4,5是某棧的壓入順序,序列4,5,3,2,1是該壓棧序列對應的一個彈出序列,但4,3,5,1,2就不可能是該壓棧序列的彈出序列。(注意:這兩個序列的長度是相等的)
題目鏈接:牛客網
解題思路
使用一個棧來模擬壓入彈出操作。
import java.util.Stack;
public class Main {
public static void main(String[] args) {
int[] push = {1, 2, 3, 4, 5};
int[] pop1 = {4, 5, 3, 2, 1};
int[] pop2 = {4, 3, 5, 1, 2};
System.out.println("true: " + isPopOrder(push, pop1));
System.out.println("false: " + isPopOrder(push, pop2));
}
public static boolean isPopOrder(int[] pushA,int[] popA) {
int n = pushA.length;
Stack<Integer> stack = new Stack();
for (int pushIndex = 0,popIndex = 0;pushIndex < n;pushIndex++) {
stack.push(pushA[pushIndex]);
while(popIndex < n && !stack.isEmpty() && stack.peek() == popA[popIndex]) {
stack.pop();
popIndex++;
}
}
return stack.isEmpty();
}
}