946. 验证栈序列(栈特性)

119 阅读1分钟

image.jpeg

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第3天,点击查看活动详情

测试岗位也越来卷了,除了基本的功能测试外,还要有编程基础、脚本经验才脱颖而出。

怎么才能提高我们的编程能力呢,刷LeetCode是最佳的途径之一,话不多数,刷题走起~

一、题目描述:

  • 题目内容

    image.png

  • 题目示例

    image.png

  • 题目解析

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

二、思路分析:

我们读取本题,题目要求给出的两个数组模拟栈入栈和出栈的对比,当入栈元素与出栈的元素结果一样时,返回True否则返回False,在进行刷题前我们还需要对题目中细节进行了解:

  • 栈的特点:先进后出
  • 两个序列pushed和popped两个数组,一个入栈的顺序和一个是出栈顺序
  • pushed和popped数组中的元素互不相同

了解本题内容后,解答该题我们可以直接使用模拟栈的方式来解答,思路如下:

  • 方法一:使用数组模拟栈

    • 定义一个临时数组stk,将pushed元素分别入栈到stk中
    • 同时定义一个index索引位置指向popped数组的起始位置
    • 使用for循环遍历pushed数组中的元素num,将其添加到stk
    • 在while循环中stk顶部的元素与popped数组中index元素对比
    • 当stk[-1]与popped[index]相等时,stk将顶部元素进行出栈处理且index进行+1
    class Solution(object):
        def validateStackSequences(self, pushed, popped):
            """
            :type pushed: List[int]
            :type popped: List[int]
            :rtype: bool
            """
            stk = []
            index = 0
            for num in pushed:
                stk.append(num)
                while stk and stk[-1] == popped[index]:
                    stk.pop()
                    index +=1
    
            return False if len(stk) != 0 else True
    
  • 方法二:使用栈特性

    • 栈的特点是:先进后出,
    • push的下一个只能是pop前一个或后面的
    class Solution(object):
        def validateStackSequences(self, pushed, popped):
            """
            :type pushed: List[int]
            :type popped: List[int]
            :rtype: bool
            """
            for i in range(len(popped) - 1):
                item = popped[i]
                ind = pushed.index(item)
                item_next = popped[i + 1]
                ind_next = pushed.index(item_next)
                if not (ind_next == ind - 1 or ind_next > ind):
                    return False
                pushed.pop(ind)
    
            return True
    

三、总结:

本题考察对出入栈过程的模拟先入后出原则,入栈的元素一定是出栈元素前一个或者后面一个。我们可以直接使用临时数组来模拟入栈出栈过程,while循环中对比popped数组的元素,直到对pushed和popped数组中元素遍历完成后,stk为空则代表栈序列正常,AC提交记录如下: image.png

  • 时间复杂度:O(n),
  • 空间复杂度:O(n),

以上是本期内容,欢迎大佬们点赞评论,下期见~~~