面试题31:栈的压入、弹出序列
题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如 {1, 2, 3, 4, 5} 是某栈的压栈序列,序列 {4, 5, 3, 2, 1} 是该栈序列对应的一个弹出序列,但 {4, 3, 5, 1, 2} 就不可能是该压栈序列的弹出序列。
思路:
- 以弹出序列 {4, 5, 3, 2, 1} 为例,第一个希望被弹出的是数字 4,因此需要 4 入栈。压入栈的顺序由压栈序列确定,也就是在把 4 压入栈之前,数字 1,2, 3都需要压入栈。此时栈中包含 4 个数字,1,2,3,4,其中 4 位于栈顶。把 4 弹出栈后,剩下的数字 1,2, 3。接下来希望弹出的元素是 5,由于它不是栈顶元素,因此我们继续将入栈序列中的元素压入辅助栈,直到压入数字 5。这时 5 位于栈顶,就可以被弹出来了。接下来希望弹出的是3, 2, 1,依次弹出即可
- 接下来分析弹出序列 {4, 3, 5, 1, 2}。按照上面的方法我们发现,4,3,5 可以正常弹出,这时栈中元素为 2,1。于是无法弹出元素 1。因此,这种弹出序列是错误的。
代码实现:
package Question31;
import java.util.Stack;
public class T01 {
public static void main(String[] args) {
int[] pushed = {1, 2, 3, 4, 5};
int[] popped = {4, 3, 5, 1, 2};
System.out.println(solve(pushed, popped));
}
public static boolean solve(int[] pushed, int[] popped) {
if(pushed == null || pushed.length == 0 || popped == null || popped.length == 0 || pushed.length != popped.length)
return false;
Stack<Integer> stack = new Stack<>();
int index1 = 0, index2 = 0;
while(index2 < popped.length) {
while(stack.empty() || stack.peek() != popped[index2]) {
if(index1 >= pushed.length) return false;
else stack.push(pushed[index1++]);
}
stack.pop();
index2++;
}
return true;
}
}