剑指Offer-Python-栈的压入、弹出序列

题目:栈的压入、弹出序列

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

思路:定义一个列表l,用来存放当前栈中的元素。
1)判断popV[0]是否在pushV中,如果在则求出其在pushV中的索引c_index。否则返回False;
2)将pushV[:c_index]压入栈l。
3)pre_index = c_index,对popV[1:]进行遍历:
a.如果当前值正好是栈l的栈顶,则出栈,继续遍历;
b.求出当前遍历元素的索引c_index,如果c_index > pre_index+1,则将pushV[pre_index+1:c_index]压入l,继续遍历;
c.否则return False
4)遍历结束,return True。

代码

# -*- coding:utf-8 -*-
class Solution:
    def IsPopOrder(self, pushV, popV):
        # write code here
        if popV is None:
            return None
        pop_num = 0
        try:
            c_index = pushV.index(popV[0])
        except ValueError:
            return False
        l = pushV[:c_index]
        for i in range(1, len(popV)):
            pre_index = c_index
            if popV[i] == l[-1]:
                l.pop(-1)
                pop_num += 1
                continue
            try:
                c_index = pushV.index(popV[i])
            except ValueError:
                return False
            if c_index > pre_index:
                if pre_index + 1 != c_index:
                    l.extend(pushV[pre_index+1:c_index])
            else:
                return False
        return True

版本二;

# -*- coding:utf-8 -*-
class Solution:
    def IsPopOrder(self, pushV, popV):
        stack = []
        while popV:
            # 如果pushV不空,且与popV头元素都相同,则出栈
            if pushV and pushV[0] == popV[0]:
                pushV.pop(0)
                popV.pop(0)
            # 如果不满足前面的条件,判断stack是否为空,不为空则判断stack[-1]与popV[0]是否相等,相等则出栈。
            elif stack and stack[-1] == popV[0]:
                popV.pop(0)
                stack.pop(-1)
            # 如果pushV不空则,stack入栈
            elif pushV:
                stack.append(pushV.pop(0))
            # 最后说明pushV为空,且stack[-1]与popV[0]不相同,则出栈序列有误,返回False
            else:
                return False
        return True

猜你喜欢

转载自blog.csdn.net/qq_34364995/article/details/81477676