其他分享
首页 > 其他分享> > 力扣 - 剑指 Offer 31. 栈的压入、弹出序列

力扣 - 剑指 Offer 31. 栈的压入、弹出序列

作者:互联网

题目

剑指 Offer 31. 栈的压入、弹出序列

思路1

代码

class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        // 用于模拟的栈
        LinkedList<Integer> stack = new LinkedList<>();
        // 用于popped数组的索引
        int index = 0;

        // 进行模拟
        for (int i = 0; i < pushed.length; i++) {
            // 每次都入栈一个元素
            stack.push(pushed[i]);
            // 查看栈顶的元素和popped的元素是否一样,一样的话,我们就模拟出栈
            // 这里index不能越界,且模拟栈不能为空:这样才能进行比较
            while (!stack.isEmpty() && popped[index] == stack.peek()) {
                stack.pop();
                index++;
            }
        }
        // 如果最终模拟的栈是空的,说明符合弹出顺序
        return stack.isEmpty();
    }
}

复杂度分析

标签:index,popped,压入,int,31,元素,力扣,stack,模拟
来源: https://www.cnblogs.com/linzeliang1222/p/15527058.html