NOWCODER 剑指offer 栈的压入、弹出序列

运行时间:29ms

占用内存:5860k

一次通过(除了开头检查pop序列数字是不是在push中存在)

思路是:但凡取了一个元素,说明元素前的所有元素都必然已经在栈中。开辟一个left序列保存一定已经在栈中的元素,所以下次取元素的时候一定不能取除最末尾外的其他在left中的元素。下次再取元素,则又将此元素前的元素加入left序列中。

# -*- coding:utf-8 -*-
class Solution:
    def IsPopOrder(self, pushV, popV):
        # write code here
        for i in popV:
            if i not in pushV:
                return False
        i = pushV.index(popV[0])
        left = pushV[:i]
        print(left)
        cnt = 0
        while (left):
            cnt += 1
            ii = pushV.index(popV[cnt])
            if ii>i-1:
                left += pushV[i+1:ii]
            else:
                if (left.index(popV[cnt]) < len(left)-1):
                    return False
                else:
                    left.pop()                
            print(ii,left)
            i = ii
        return True

——————————————————————————————————————

看到了别人很妙的思路,那就是模仿pop数列进行栈入栈出

运行时间:21ms

占用内存:5864k

# -*- coding:utf-8 -*-
class Solution:
    def IsPopOrder(self, pushV, popV):
        # write code here
        for i in popV:
            if i not in pushV:
                return False
        stack = []
        for i in pushV:
            stack.append(i)
            while (stack and popV[0]==stack[-1]):
                stack.pop()
                popV.pop(0)
        if not stack:
            return True
        else:
            return False

猜你喜欢

转载自blog.csdn.net/u014381464/article/details/82019115