[剑指Offer]栈的压入弹出序列[Python]

题目要求:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

解题思路:当前出栈为a,则下一个出栈的数字在入栈序列中,可以是排在它后面的任意一项,也可以是他前面的项,但跟她的索引值之差不能大于1.需要注意的是它也可能不在原来的序列中,所以要先判断它是否存在,在用.index函数找索引


# -*- coding:utf-8 -*-

class Solution:
    def IsPopOrder(self, pushV, popV):
        # write code here
        list_len = len(pushV)
        for i in range(len(popV)):
            pop_num = popV.pop(0)
            if pushV.count(pop_num):
                
                index = pushV.index(pop_num)
                if popV:
                    if pushV[index:len(pushV)].count(popV[0]) or (pushV[0:index].count(popV[0]) and abs(pushV[0:index].index(popV[0])- index)==1):
                        pushV.pop(index)
                    else:
                        return False
                else:
                    return True
            else:

                return False

看大家还有一个思路:引入辅助栈来模拟出栈的顺序,挺直观的

链接:https://www.nowcoder.com/questionTerminal/d77d11405cc7470d82554cb392585106
来源:牛客网

# -*- coding:utf-8 -*-
class Solution:
    def IsPopOrder(self, pushV, popV):
        # write code here
        #辅助栈,存放压入元素
        stack = []
        #弹出栈的元素下标
        count = 0
        if not pushV or not popV:
            return False
        for i in range(len(pushV)):
            stack.append(pushV[i])
            #当辅助栈不为空且栈顶元素等于弹出元素时,将栈顶元素弹出,count +1
            while stack and stack[-1] == popV[count]:
                stack.pop()
                count+= 1
        return not stack

猜你喜欢

转载自blog.csdn.net/jillian_sea/article/details/80339471