[算法学习]栈的出栈序列

问题描述: 输入数字不重复的两组整数序列:压栈的序列A,出栈的序列B,验证AB是否为同一栈的序列。

解法与分析:

  1. 使用两个指针pA,pB分别在两个序列A,B上遍历。
  2. 做个这样的判断,首先判断两个指针所指元素是否相等,若相等,则两个指针同时推进;若不相等,取出栈顶元素作比较;若与栈顶元素不相等,则序列A的元素入栈,pA指针向前推进,若与栈顶元素相等,则出栈,pB指针推进。

参考代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public static boolean isStackSeq(int[] pushSeq, int[] popSeq)
{

if (popSeq == null || pushSeq == null
|| pushSeq.length != popSeq.length)
{
return false;
}
Stack<Integer> stack = new Stack<Integer>();
int pushIndex = 0;
int popIndex = 0;

while (popIndex < popSeq.length)
{
if (pushIndex < pushSeq.length)
{
if (pushSeq[pushIndex] == popSeq[popIndex])
{
pushIndex++;
popIndex++;
continue;
}
if (!stack.isEmpty() && stack.peek() == popSeq[popIndex])
{
stack.pop();
popIndex++;
}
else
{
stack.push(pushSeq[pushIndex++]);
}
}
else if (!stack.isEmpty() && stack.pop() == popSeq[popIndex])
{
popIndex++;
}
else
{
return false;
}
}
return stack.isEmpty();
}