思路:创建栈,并且两个指针指向数组,直到pop数组结束,或者stack空了
static boolean check(int[] push, int[] pop) {
if (push==null || pop==null)
return false;
int pushIndex=0;
int popIndex=0;
Stack<Integer> stack = new Stack<>();
// 进行最初的判断
for (pushIndex = 0; pushIndex < push.length; pushIndex++) {
if (push[pushIndex]==pop[0]){
popIndex++;
pushIndex++;
break;
}
stack.push(push[pushIndex]);
}
while (!stack.isEmpty() && popIndex<pop.length) {
while (!stack.isEmpty() && stack.peek() == pop[popIndex]) {
stack.pop();
popIndex++;
}
// 如果pop已经结束了
if (popIndex > pop.length-1)
break;
// 如果下一个pop的数字在stack里面
if (stack.contains(pop[popIndex])) {
while (!stack.isEmpty()) {
if (stack.peek()==pop[popIndex]) {
stack.pop();
popIndex++;
break;
}
stack.pop();
}
} else {
// 如果不在stack里面
// 对push数组继续进行循环,添加进去,直到找到或者结束
for (;pushIndex<push.length;pushIndex++) {
if (push[pushIndex] == pop[popIndex]) {
pushIndex++;
popIndex++;
break;
}
stack.push(push[pushIndex]);
}
}
}
return stack.isEmpty() && pushIndex == push.length && popIndex == pop.length;
}
public static void main(String[] args) {
int[] push = {1,2,3,4,5};
int[] pop = {4,3,5,1,2};
int[] pop1 = {5,4,3,2,1};
System.out.println(check(push, pop1));
}