思路:用一个栈进行模拟,当栈不为空且栈顶元素与出栈数组的元素相等时,元素出栈,出栈元素后移,继续与栈顶元素对比,如此反复
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stk = new Stack<>();//用一个栈进行模拟
int i = 0;
for(int elem : pushed){
stk.add(elem);
while(!stk.isEmpty()&&i < popped.length&&stk.peek() == popped[i] ){//注意条件顺序,否则可能造成nullpointer
stk.pop();
i++;
}
}
return i == pushed.length;
}
}