您的位置:首页 > 职场人生

剑指offer面试题 22 栈的压入、弹出序列的匹配

2016-07-25 15:17 369 查看
不多说,上代码

package sword.to.offer;

import java.util.Stack;

public class IsPopOrder {

static boolean isPopOrder(final int[]pPush,final int[] pPop,int nLegnth){
boolean bImpossible=false;

if(pPush.length!=0&&pPop.length!=0){
java.util.Stack<Integer> stack=new Stack<Integer>();
int i=0;
int j=0;
while(j<nLegnth){
while(stack.isEmpty()||stack.peek()!=pPop[j])
{
if(i==nLegnth){
break;
}
stack.push(pPush[i]);
i++;
}
if(stack.peek()!=pPop[j])
break;
stack.pop();
j++;
}
if(stack.isEmpty()&&j==nLegnth)
bImpossible=true;
}
return bImpossible;

}

public static void main(String[] args) {
//若要验证b是a完整的pop弹出序列,各数组的个数必须
int[] a={1,2,3,4,5};
int[] b= {4,5,3,2,1};
int[]c={4,3,5,1,2};
System.out.println(isPopOrder(a, b,5));
System.out.println(isPopOrder(a, c,5));
}
}
运行结果:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  剑指offerJava实现