用一个栈模拟栈的压入弹出序列,先遍历push序列,压入栈,然后看此时栈的顶部是否等于poped[i],如果等于的话就弹出栈,i++。最后看是否stack.isEmpty()。
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stack=new Stack<>();
int i=0;
for(int num:pushed){
stack.push(num);
while(!stack.isEmpty()&&stack.peek()==popped[i]){
stack.pop();
i++;
}
}
return stack.isEmpty();
}
}