题解 | #栈的压入、弹出序列#
栈的压入、弹出序列
http://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106
# -*- coding:utf-8 -*-
class Solution:
def IsPopOrder(self, pushV, popV):
# write code here
stack = []
pushIdx = 0
popIdx = 0
while True:
# print("pushIdx:%d,len(pushV):%d, popidx:%d" %(pushIdx, len(pushV), popIdx))
if pushIdx >= len(pushV) and (len(stack)>0 and stack[-1] != popV[popIdx]):
return False
if pushIdx >= len(pushV) and popIdx == pushIdx:
return True
if len(stack)==0:
for item in pushV[pushIdx:]:
stack.append(item)
pushIdx += 1
if item == popV[popIdx]:
popIdx += 1
stack.pop()
break
# print(pushIdx, popIdx)
else:
if stack[-1] == popV[popIdx]:
popIdx += 1
stack.pop()
else:
for item in pushV[pushIdx:]:
stack.append(item)
pushIdx += 1
if item == popV[popIdx]:
popIdx += 1
stack.pop()
break
return True
class Solution:
def IsPopOrder(self, pushV, popV):
# write code here
stack = []
pushIdx = 0
popIdx = 0
while True:
# print("pushIdx:%d,len(pushV):%d, popidx:%d" %(pushIdx, len(pushV), popIdx))
if pushIdx >= len(pushV) and (len(stack)>0 and stack[-1] != popV[popIdx]):
return False
if pushIdx >= len(pushV) and popIdx == pushIdx:
return True
if len(stack)==0:
for item in pushV[pushIdx:]:
stack.append(item)
pushIdx += 1
if item == popV[popIdx]:
popIdx += 1
stack.pop()
break
# print(pushIdx, popIdx)
else:
if stack[-1] == popV[popIdx]:
popIdx += 1
stack.pop()
else:
for item in pushV[pushIdx:]:
stack.append(item)
pushIdx += 1
if item == popV[popIdx]:
popIdx += 1
stack.pop()
break
return True