0946.验证栈顺序
描述
给定 pushed
和 popped
两个序列,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列的结果时,返回 true
;否则,返回 false
。
实例
输入: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
输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
输出:false
解释:1 不能在 2 之前弹出。
提示
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed
是popped
的排列。
题解
根据当前状态判断能否满足pop
- 判断当前需要
pop
的值是否和下一个需要push
的值相同,- 如果是则满足条件判断下一个
pop
的值 - 如果不是则判断当前栈顶元素是否相同,
- 相同则弹出栈顶元素并判断下一个
pop
值 - 如果与与栈顶元素不匹配则入栈下一个
push
并继续比较- 如果没有可以入栈的元素则返回
false
- 否则返回
true
- 如果没有可以入栈的元素则返回
- 相同则弹出栈顶元素并判断下一个
- 如果是则满足条件判断下一个
public static boolean validateStackSequences(int[] pushed, int[] popped) {
if (popped.length == 0)
return true;
int pushIndex = 0;
int popIndex = 0;
int length = popped.length;
Stack<Integer> stack = new Stack<>();
stack.push(pushed[pushIndex++]);
while (popIndex != length){
int nowPop = popped[popIndex];
if (pushIndex > length && nowPop == pushed[pushIndex]){
popIndex++;
pushIndex++;
} else {
if (!stack.empty() && stack.peek() == nowPop){
stack.pop();
popIndex++;
} else
if (pushIndex < length)
stack.push(pushed[pushIndex++]);
else
return false;
}
}
return true;
}