栈的压入、弹出序列

思路:用一个栈进行模拟,当栈不为空且栈顶元素与出栈数组的元素相等时,元素出栈,出栈元素后移,继续与栈顶元素对比,如此反复

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;
    }
}

posted @ 2020-07-23 21:51  浅滩浅  阅读(96)  评论(0编辑  收藏  举报