
按照pushed数组的顺序入栈,按照poped数组的顺序出栈,最后栈中为空就可以返回true,否则返回false。
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stack = new Stack<Integer>();
int index = 0;
//一直遍历pushed数组把数据压入栈中,直到遇到stack栈顶的数和poped数组的数一样的数据
//如上方是示例1,pushed数组一直入栈直到4的时候,才出栈,因为poped数组也有一个4
for(int i = 0;i < pushed.length;i++){
//数据压入栈中
stack.push(pushed[i]);
//栈不为空且pushed数组和poped数组有相同的数
while(!stack.isEmpty() && stack.peek() == popped[index]){
//将当前的数据弹出
stack.pop();
//poped数组继续往后遍历
index++;
}
}
//最后整个栈都为空了返回true,否则返回false
if(!stack.isEmpty()){
return false;
}else{
return true;
}
}
}
验证栈序列操作:按顺序推入和弹出
本文介绍了一种算法,用于判断给定的两个整数数组(pushed和popped)是否可以按照特定顺序实现栈的入栈和出栈操作。通过构造栈并检查每个元素是否对应出栈,最后判断栈是否为空来确定答案。
283

被折叠的 条评论
为什么被折叠?



