题目
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。
解题思路
这题很简单,主要的模拟逻辑为使用堆栈去模拟先进后出,先定位到pop数组的第一个元素, 然后将push之前的元素全部压入stack中,然后我这边直接跳过要出栈的那个元素,遍历到第二个pop的元素, 如果是之前已经在stack中的元素则直接pop,不然也是遍历push直到遍历到这个pop元素,然后开启第三轮的遍历, 主要的模拟逻辑就是这些, 具体代码如下。
Java代码实现
import java.util.Stack;
public class ValidateStackSequences {
public static boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stack = new Stack();
int startIndex = 0;
for (int j = 0; j < popped.length; j++) {
int firstPop = popped[j];
if (!stack.isEmpty()) {
if (stack.peek() == firstPop) {
stack.pop();
continue;
}
}
for (int i = startIndex; i < pushed.length; i++) {
if (firstPop != pushed[i]) {
stack.add(pushed[i]);
startIndex = i;
} else {
i++;
startIndex = i;
break;
}
}
}
if (stack.isEmpty()) {
return true;
} else {
return false;
}
}
}