【分析】这个其实只要用真正的栈去模拟就行,根据popped的顺序来确定pushed的入栈顺序,其中一个非常重要的依据就是,当popped出现某个数字时,那么在pushed的这个数字之前的就已经进栈了。
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Deque<Integer> stack = new LinkedList();
int i = 0, j = 0, n = pushed.length;
while(j < n){
if(stack.isEmpty() && i < n){
stack.push(pushed[i++]);
}else{
while(stack.peek() != popped[j] && i < n){
stack.push(pushed[i++]);
}
if(stack.poll() != popped[j]) return false;
else j++;
}
}
return true;
}
}