• Killing LeetCode [946] 验证栈序列


    Description

    给定 pushed 和 popped 两个序列,每个序列中的 值都不重复,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列的结果时,返回 true;否则,返回 false 。

    Intro

    Ref Link:https://leetcode.cn/problems/validate-stack-sequences/
    Difficulty:Medium
    Tag:Stack,Back Tracking
    Updated Date:2023-09-08

    Test Cases

    示例1:

    输入:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
    输出:true
    解释:我们可以按以下顺序执行:
    push(1), push(2), push(3), push(4), pop() -> 4,
    push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
    
    • 1
    • 2
    • 3
    • 4
    • 5

    示例 2:

    输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
    输出:false
    解释:1 不能在 2 之前弹出。
    
    • 1
    • 2
    • 3

    提示:

    1 <= pushed.length <= 1000
    0 <= pushed[i] <= 1000
    pushed 的所有元素 互不相同
    popped.length == pushed.length
    popped 是 pushed 的一个排列
    
    • 1
    • 2
    • 3
    • 4
    • 5

    思路

    • 栈的特性,验证栈的入栈出栈序列
      1. 按照 pushed 顺序依次入栈;
      1. 每次入栈时,判断当前和之前入栈的索引元素是否要出栈,即栈顶元素和 poped 数组元素依次比较,直到出栈结束;
      1. 当 pushed 数组遍历完成入栈完毕,此时若按 poped 数组出栈,那么栈中应为空,返回 true;若不为空,则返回 false。

    Code AC

    class Solution {
        public boolean validateStackSequences(int[] pushed, int[] popped) {
            //if (pushed == null || popped == null || pushed.length != popped.length) return false;
            Stack stack = new Stack<>();
            int popIndex = 0;
            for (int i = 0; i < pushed.length; i++) {
                stack.push(pushed[i]);
                while(!stack.isEmpty() && stack.peek() == popped[popIndex]){
                    stack.pop();
                    popIndex++;
                }
            }
            return stack.isEmpty();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    Accepted

    152/152 cases passed (4 ms)
    Your runtime beats 16.72 % of java submissions
    Your memory usage beats 87 % of java submissions (41.9 MB)
    
    • 1
    • 2
    • 3

    复杂度分析

    • 时间复杂度:O(n),其中 n 是数组 pushed 和 popped 的长度。
    • 空间复杂度:O(n),其中 n 是数组 pushed 和 popped 的长度。
  • 相关阅读:
    如何安装Xftp实现上传和下载文件
    cmake使用
    两天写一个电影资讯速览微信小程序(附源码)
    SourceTree配置代理详细方法
    盲目跟风考PMP认证?PMP还剩多少含金量?
    移动WEB开发之流式布局--移动端基础
    Mysql安装
    建造者模式
    保健品行业正在升级,你准备好了吗?
    Spring-MVC使用JSR303及拦截器,增强网络隐私安全
  • 原文地址:https://blog.csdn.net/m0_37292477/article/details/132762817