按照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;
}
}
}