剑指 Offer 31. 栈的压入、弹出序列
思路
每次入栈后都进行检测,如果当前栈顶元素等于出栈序列的元素就弹出,循环直到不相等,最后判断栈是否为空
代码
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> st2=new Stack<>();
int j=0;
for(int i=0;i<pushed.length;i++){
st2.push(pushed[i]);
while(j<popped.length&&!st2.isEmpty()&&popped[j]==st2.peek()){
st2.pop();
j++;
}
}
return st2.isEmpty();
}