题目描述:
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。
例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,
但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
思路:
思路:模拟压栈和弹栈的序列
1. 需要一个压入栈,来模拟压入的顺序
2. 按照入栈序列来压栈,每次压栈比较栈顶和弹出序列的首部是否相同
a.若相同,压入栈弹出栈顶元素并且出栈序列弹出序列首部元素
b.若不相同,压入栈继续压入并且比较。
3. 若 入栈序列已经完毕,但是出栈序列还不为空,证明不是对应的弹出序列。
代码
public class IsPopOrder {
public static boolean isPopOrder(int[] pushA, int[] popA) {
if (pushA.length != popA.length || pushA.length <= 0 || popA.length <= 0)
return false;
int pushIdx = 0;
int popIdx = 0;
Stack<Integer> s = new Stack<>();
while (pushIdx < pushA.length) {
s.push(pushA[pushIdx]);
while ( !s.empty() && s.peek() == popA[popIdx]) {
s.pop();
popIdx++;
}
pushIdx++;
}
if (popIdx == popA.length)
return true;
return false;
}
public static void main(String[] args) {
int[] pushA = {1, 2, 3, 4, 5};
int[] popA = {4, 5, 3, 2, 1};
System.out.println(isPopOrder(pushA, popA));
}
}