题目:
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列 { 1, 2, 3, 4, 5 } 是某栈的压入顺序,序列 { 4, 5, 3, 2, 1 } 是该压栈序列对应的一个弹出序列,但 { 4, 3, 5, 1, 2 } 就不可能是该压栈序列的弹出序列。
分析一:
用一个栈来模拟这个过程,当栈顶元素等于序列的第一个数时,出栈的同时要使序列的下标再往后移一位。
代码一:
package offer.xzs.thirty2thirtynine.thirtyone;
import java.util.Stack;
public class Demo01 {
public static void main(String[] args) {
int[] arr1 = { 1, 2, 3, 4, 5 };
int[] arr2 = { 4, 3, 5, 1, 2 };
boolean judge = judge(arr1, arr2);
System.out.println(judge);
}
public static boolean judge(int[] arr1, int[] arr2) {
Stack<Integer> stack = new Stack<>();
for (int i = 0, j = 0; i < arr1.length; i++) {
stack.push(arr1[i]);
while (j < arr1.length && !stack.isEmpty() && stack.peek() == arr2[j]) {
stack.pop();
j++;
}
}
return stack.isEmpty();
}
}