+ 先给一个空列表stack,用作过渡,我们先把pushV中的值都弹出存放到stack中,一开始给一个索引index = 0,然后每次都让stack的最后一位和popV的 index 进行比较,如果相同就弹出,否则就继续向后找,最后如果 stack 为空,也就是说是stack里的数刚好弹完,即popV就是pushV的弹出序列,那么就返回True,反之,返回False。
# -*- coding:utf-8 -*- class Solution: def IsPopOrder(self, pushV, popV): # write code here if not pushV and len(pushV) != len(popV): return False stack = [] index = 0 for item in pushV: stack.append(item) while stack and stack[-1] == popV[index]: stack.pop() index += 1 if not stack: return True else: return False