题目(难度:中等):
给定 pushed 和 popped 两个序列,每个序列中的 值都不重复,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列的结果时,返回 true;否则,返回 false 。
示例 1:
输入:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
输出:true
解释:我们可以按以下顺序执行:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
示例 2:
输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
输出:false
代码思想:
题目给出两个数组,一个输入序列,一个输出序列,验证该输出序列是否是该输入数组的一个序列。如果不能利用输入数组模拟栈的先进后出的特点的话,需要借助额外空间栈,将输入数组逐一放入栈,并判断入栈元素是否与输出序列元素相同,如果相同则出栈,输出序列向后移动,否则继续入栈。判断是否是其序列的条件是输出序列的移动指针等于其长度,说明全部匹配。
代码实现:
public boolean validateStackSequences(int[] pushed, int[] popped) {
if (pushed.length == 0 && popped.length == 0) return true;
if (pushed.length == 0 && popped.length != 0 || pushed.length != 0 && popped.length == 0 || pushed.length != popped.length)
return false;
Stack<Integer> stack = new Stack<>();
int len = pushed.length;
int index = 0;
for (int i = 0; i < len; i++) {
stack.push(pushed[i]);
while (!stack.isEmpty() && index < len && stack.peek() == popped[index]) {
stack.pop();
index++;
}
}
return index == len;
}
测试用例:
算法分析:
时间复杂度最大为O(n*n),额外空间复杂度为O(n)