0
点赞
收藏
分享

微信扫一扫

微软100题-天天做-第29题


29.栈的push、pop序列(栈)
题目:输入两个整数序列。其中一个序列表示栈的push顺序,
判断另一个序列有没有可能是对应的pop顺序。
为了简单起见,我们假设push序列的任意两个整数都是不相等的。 

比如输入的push序列是1、2、3、4、5,那么4、5、3、2、1就有可能是一个pop系列。
因为可以有如下的push和pop序列:
push 1,push 2,push 3,push 4,pop,push 5,pop,pop,pop,pop,
这样得到的pop序列就是4、5、3、2、1。
但序列4、3、5、1、2就不可能是push序列1、2、3、4、5的pop序列。

 

 

package com.microsoft;

public class PushPopSeqence {
private int[] pushSeq;
private int[] popSeq;
private boolean[] popEd;

public PushPopSeqence(int[] pushSeq, int[] popSeq) {
this.pushSeq = pushSeq;
this.popSeq = popSeq;
popEd = new boolean[pushSeq.length];
}

public boolean judge() {
int index = -1;
int indexBefore = -1;
for (int i = 0; i < popSeq.length; i++) {
for (int j = 0; j < pushSeq.length; j++) {
if (pushSeq[j] == popSeq[i]) {
index = j;
break;
}
}
if (index == -1) {
return false;
} else {
if (indexBefore != -1) {
if (index > indexBefore) {
for (int j = indexBefore; j < index; j++) {
if (!popEd[j]) {
return false;
}
}
} else if (index < indexBefore) {
for (int j = index+1; j <=indexBefore; j++) {
if (!popEd[j]) {
return false;
}
}
}
}

popEd[index] = true;
indexBefore = index;
}

}
return true;
}

public static void main(String[] args) {
int[] push = new int[] { 1, 2, 3, 4, 5 };
int[] pop1 = new int[] { 4, 5, 3, 2, 1 };
int[] pop2 = new int[] { 4, 3, 5, 1, 2 };
PushPopSeqence seq = new PushPopSeqence(push, pop1);
System.out.println(seq.judge());
PushPopSeqence seq2 = new PushPopSeqence(push, pop2);
System.out.println(seq2.judge());
}

}

 

 

 

 

 

举报

相关推荐

0 条评论