标签:
问题描述
输入两个整数序列,其中一个为入栈序列,另一个为出栈序列。判断出栈序列是否是合法的。
解决思路
使用一个辅助栈,用最直观的方式。
程序
public class ValidPopSequence {
public boolean isValidPopSeq(int[] push, int[] pop) {
if (push == null && pop == null) {
return true;
}
int i = 0, j = 0;
Stack<Integer> s = new Stack<Integer>();
while (j < pop.length) {
while (i < push.length) {
if (push[i] != pop[j]) {
s.push(push[i]);
++i;
} else {
// same, no push, pop next
++i;
++j;
break;
}
}
if (i == push.length) {
// end push
// check top of stack with pop
if (s.isEmpty() || s.peek() != pop[j]) {
return false;
}
s.pop();
++j;
}
}
return true;
}
}
标签:
原文地址:http://www.cnblogs.com/harrygogo/p/4635099.html