LeetCode 剑指offer Q31栈的压入、弹出序列

思路

通过使用一个辅助栈,来模拟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;
    }
}
发布了42 篇原创文章 · 获赞 0 · 访问量 1945

猜你喜欢

转载自blog.csdn.net/c630565685/article/details/104802069