栈压入、弹出序列

这道题需要检测弹出序列是否是真的是对应压入序列其中一个正确的值,既然这样的话,我们可以利用双指针,每次一开始先把push中的值压入栈,直到当前元素等于pop序列的当前元素,我们停止压入,开始倒出元素,就这样往复循环到最后,如果两根指针都指向末尾,则说明序列是合法的,自己的代码思路比较清晰

class Solution:
    def IsPopOrder(self, pushV, popV):
        # write code here
        stack = []
        curPush, curPop = 0, 0
        n = len(pushV)
        if len(pushV) != len(popV):
            return False

        while curPush < n:
            while curPush < n and pushV[curPush] != popV[curPop]:
                stack.append(pushV[curPush])
                curPush += 1
            if curPush < n:
                stack.append(pushV[curPush])
                curPush += 1
            while stack and stack[-1] == popV[curPop]:
                stack.pop()
                curPop += 1

        return curPush == n and curPop == n

还有讨论区一种更加优雅的写法,虽然我觉得我自己这个也很好了

class Solution:
    def IsPopOrder(self, pushV, popV):
        # write code here
        if len(pushV) != len(popV):
            return False

        n = len(pushV)
        stack = []
        j = 0
        for i in xrange(n):
            stack.append(pushV[i])
            while stack and stack[-1] == popV[j]:
                stack.pop()
                j += 1
        return j == n

results matching ""

    No results matching ""