牛客网的剑指Offer的一道题目。
对于第二个数组而言,遍历第一个数组,如果不相同就压入栈,相同的话就压入栈再出栈。当第二个数组遍历结束后,如果栈为空,就是true,反之,就是false.
public static boolean IsPopOrder(int [] pushA,int [] popA) {
Stack<Integer> stack=new Stack<Integer>();
int m=0;
for (int i = 0; i < popA.length; i++) {
//如果栈顶元素等于当前的元素,就抛出
if(stack.size()>0&&stack.peek()==popA[i])
{
stack.pop();
continue;
}
while(m<pushA.length &&pushA[m]!=popA[i])
{
stack.push(pushA[m]);
m++;
}
if(m<pushA.length)
{
stack.push(pushA[m]);
m++;
stack.pop();
}
}
if(stack.size()>0)
{
return false;
}
else
{
return true;
}
}