題目
輸入兩個整數序列,第一個序列表示棧的壓入順序,請判斷第二個序列是否爲該棧的彈出順序。假設壓入棧的所有數字均不相等。例如序列1,2,3,4,5是某棧的壓入順序,序列4,5,3,2,1是該壓棧序列對應的一個彈出序列,但4,3,5,1,2就不可能是該壓棧序列的彈出序列。(注意:這兩個序列的長度是相等的)
思路
壓入棧的同時不斷判斷是否爲序列
代碼
# -*- coding:utf-8 -*-
class Solution:
def IsPopOrder(self, pushV, popV):
# write code here
stack = []
i = 0; j = 0
while i < len(pushV) and j < len(popV):
stack.append(pushV[i])
i += 1
while stack and stack[-1] == popV[j]:
stack.pop(-1)
j += 1
return False if stack else True