首页 > 其他 > 详细

【LeetCode】面试题31. 栈的压入、弹出序列

时间:2020-06-09 11:41:49      阅读:31      评论:0      收藏:0      [点我收藏+]

题目:

技术分享图片

思路:

贪心思想按照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

相关问题

【LeetCode】面试题31. 栈的压入、弹出序列

原文:https://www.cnblogs.com/cling-cling/p/13071508.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!