思路
通过使用一个辅助栈,来模拟pushed数组进入栈中的过程。在将每个pushed元素压入栈时,使用一个while循环判断当前栈顶是否和poped相同,若相同都进行弹出。
最后若栈为空则说明正确,否则错误。
代码
class Solution {
public boolean validateStackSequences(int[] pushed, int[] popped) {
//Stack<Integer> s=new Stack<>();
int[] st=new int[1001];
int end=-1;
int len=pushed.length;
if(len==0) return true;
int j=0;
for(int i=0;i<len;i++){
st[++end]=pushed[i];
//s.add(pushed[i]);
while(end!=-1&&j<len&&popped[j]==st[end]){
//s.pop();
end--;
j++;
}
}
return end<0;
}
}