输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。
import java.util.Stack;
/**
*
* @author 过路的守望
* 判断一个序列是否为某一个序列的出栈序列。 模拟入栈和出栈的过程,查看是否一致。 详细思路如下:
* 举例:入栈序列为1,2,3,4,5 某一序列为 2,3,1,4,5 。首先选择1
* 入栈,然后查看序列2是否相同,不同说明没有出栈,继续入栈2,继续查看
* 相同,说明2出栈,然后继续查看是否相同1和3不同,继续入栈3,查看和序列2中的头元素3一致,出栈,继续查看序列1中的1,和序列2中的1
* 一致,然后出栈。。。直到最终序列2为空;如果最后发现序列1为空的时候序列2中仍然有元素,则说明不是合法出栈序列;
*/
public class IsPopOrder {
public static void main(String[] args) {
int[] push = {1,2,3,4,5};
int[] pop = {1,2,5,3,4};
System.out.println(new IsPopOrder().isPopOrder(push, pop));
}
public boolean isPopOrder(int[] push, int[] pop) {
int a_len = push.length;
int b_len = pop.length;
if (a_len != b_len || a_len == 0) {
return false;
}
int j = 0;
/*
* 辅助栈
*/
Stack<Integer> stack = new Stack<Integer>();
for (int i = 0; i < a_len; i++) {
stack.push(push[i]);
if (stack.peek() != pop[j]) {
continue;
}
while (!stack.isEmpty()) {
if (stack.peek() == pop[j]) {
stack.pop();
j++;
} else {
break;
}
}
}
return stack.isEmpty();
}
}