import java.util.Stack;
/**
* isPopOrder 根据栈的入栈序列来判断某一序列是否为该栈的弹出序列。
*/
public class StackUtil {
/**
* 输入两个整数序列,第一个序列表示栈的压入顺序,请判断二个序列是否为该栈的弹出顺序,假设压入栈的所有数字均不相等。
* eg:序列1,2,3,4,5是某个栈的压栈序列,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不是该压栈序列的弹出序列。
*
* 思路:
* 1)建立一个辅助栈,然后遍历出栈序列,并判断当前遍历的元素与辅助栈的栈顶元素是否相同:
* 3)若不相同,则将入栈序列中的元素依次压入辅助栈,直到辅助栈的栈顶元素与当前遍历的元素相同,若将入栈序列中的元素全部压入后,辅助栈的栈顶元素仍然与当前遍历的元素不同,则说明出栈序列不是该栈的弹出序列。
* 2)若相同,则将辅助栈的栈顶元素弹出,然后再遍历出栈序列的下一个元素;
*
* @param pushSeq 入栈序列
* @param popSeq 出栈序列
* @return
*/
public static boolean isPopOrder(int[] pushSeq, int[] popSeq) {
if (pushSeq == null || popSeq == null || popSeq.length == 0 || pushSeq.length == 0 || pushSeq.length != popSeq.length) {
return false;
}
// 创建一个辅助栈
Stack<Integer> stack = new Stack<>();
int pushSeqIndex = 0;
int popSeqIndex = 0;
// 遍历出栈序列
while (popSeqIndex < popSeq.length) {
// 当前遍历的元素与辅助栈的栈顶元素不相同
while (pushSeqIndex < pushSeq.length && (stack.isEmpty() || stack.peek() != popSeq[popSeqIndex])) {
stack.push(pushSeq[pushSeqIndex]);
pushSeqIndex++;
}
if (stack.peek() == popSeq[popSeqIndex]) { // 存在栈顶元素与当前遍历的元素与相同
stack.pop(); // 将辅助栈的栈顶元素弹出
popSeqIndex++; // 遍历出栈序列的下一个元素
} else { // 将入栈序列中的元素全部压入辅助栈后,辅助栈的栈顶元素仍然与当前遍历的元素不同
return false;
}
}
return true;
}
public static void main(String[] args) {
int[] pushReq = {1, 2, 3, 4, 5};
// int[] popReq = {4, 5, 3, 2, 1};
int[] popReq = {4, 3, 5, 1, 2};
boolean result = isPopOrder(pushReq, popReq);
System.out.println(result);
}
}