思路:使用一个栈来模拟压入弹出操作。每次入栈一个元素后,都要使用while循环来重复判断一下栈顶元素是不是当前出栈数组 popped 的第一个元素,如果是的话则执行出栈操作并将 popped的索引index 往后移一位,继续进行判断。
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stack = new Stack<>();
int index = 0;
for(int i = 0; i < pushed.length; ++i){
stack.push(pushed[i]);
while(!stack.isEmpty() && stack.peek() == popped[index]){
stack.pop();
++index;
}
}
return stack.isEmpty();
}
}