方法一
使用栈和指针,首先指针为入栈的第一个位置i,当出栈为莫一个值时,说明入栈队列在这个值之前的所有值均入栈,因此将此值在入栈队列对应的下标j到指针i中的所有下标[1, j)入栈。更新指针i = j + 1;注;此时就j > i;
若i > j, 表明,j对应值已经入栈,之间将其与栈的顶元素相比较,不相同则返回false;
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Map<Integer, Integer> hashmap = new HashMap<>();
for(int i = 0; i < pushed.length; i++){
hashmap.put(pushed[i], i);
}
Stack<Integer> stack = new Stack();
int index = 0;
for(int i = 0; i < popped.length; i++){
int new_index = hashmap.get(popped[i]);
if(new_index > index){
for(int j = index; j < new_index; j++){
stack.push(j);
}
index = new_index + 1;
}else if(new_index == index){
index ++;
}else{
if(stack.pop() != new_index) return false;
}
}
return true;
}
}
方法二
使用栈和指针,指针为出栈的第一个位置,遍历入栈队列,每次将队列的元素入栈。当栈顶元素与指针所指元素相同,出栈,并且指针向后移动,循环,直到栈为空
遍历结束时,栈为空,说明成功,返回true,否则返回false;
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stack = new Stack();
int index = 0;
for(int num : pushed){
stack.push(num);
while(!stack.isEmpty() && stack.peek() == popped[index]){
stack.pop();
index ++;
}
}
return stack.isEmpty();
}
}