zoukankan      html  css  js  c++  java
  • 【LeetCode】面试题31. 栈的压入、弹出序列

    题目:

    思路:

    贪心思想按照popped的顺序模拟栈的弹出,如果栈顶元素等于popped当前元素则立即弹出,逻辑思考。可以分别以popped和pushed作为主循环编写代码。

    代码:

    Python

    # popped作为主循环
    class Solution(object):
        def validateStackSequences(self, pushed, popped):
            """
            :type pushed: List[int]
            :type popped: List[int]
            :rtype: bool
            """
            stack = []
            if not pushed and not popped:
                return True
            if len(pushed) != len(popped):
                return False
            
            pushIndex = 0
            popIndex = 0
            while popIndex < len(popped):
                # 栈为空或者栈顶元素不匹配则入栈
                if not stack or popped[popIndex] != stack[-1]:
                    # 加入一个待匹配元素
                    if pushIndex < len(pushed):
                        stack.append(pushed[pushIndex])
                        pushIndex += 1
                    else:
                        return False
                # 栈顶元素匹配上
                else:
                    stack.pop()
                    popIndex += 1
            return True if not stack else False
    
    # pushed作为主循环(pushed和popped长度相同)
    class Solution(object):
        def validateStackSequences(self, pushed, popped):
            """
            :type pushed: List[int]
            :type popped: List[int]
            :rtype: bool
            """
            stack = []
            if not pushed and not popped:
                return True
            if len(pushed) != len(popped):
                return False
            i = 0
            for elem in pushed:
                stack.append(elem)
                while stack and popped[i] == stack[-1]:
                    stack.pop()
                    i += 1
            return not stack
    

    相关问题

  • 相关阅读:
    HDU 1856 More is better
    并查集模板
    HDU 1325 Is It A Tree?
    HDU 1272 小希的迷宫
    CodeVS 2639 约会计划
    POJ 1163 数字三角形
    HDU 1232 畅通工程
    HDU 1213 How Many Tables
    树形结构打印二叉树
    网址收藏
  • 原文地址:https://www.cnblogs.com/cling-cling/p/13071508.html
Copyright © 2011-2022 走看看