问题描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。1. 0<=pushA.length == popA.length <=1000
2. -1000<=pushA[i]<=1000
3. pushA 的所有数字均不相同
分析
实现
public boolean IsPopOrder(int[] pushA, int[] popA) {
if (pushA == null && popA == null) {
return true;
} else if ((pushA == null && popA != null) || (pushA != null && popA == null)) {
return false;
} else {
Stack<Integer> s = new Stack();
int i = 0;
int j = 0;
while (i < pushA.length) {
if (popA[j] == pushA[i]) {
i++;
j++;
} else {
if (!s.isEmpty() && popA[j] == s.peek()) {
s.pop();
j++;
} else {
s.push(pushA[i]);
i++;
}
}
}
if (j == popA.length) {
return true;
}
while (!s.isEmpty()) {//如果栈不空,能把栈清空,也是合理的出栈顺序
if (popA[j] == s.pop()) {
j++;
} else {
return false;
}
}
return true;
}
}
京公网安备 11010502036488号