剑指Offer-面试题22 栈的压入、弹出序列(python 实现)
题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
解决方案
不同于书中答案的方法
可能不是最好的方法,供参考~
没有用辅助栈 额外定义了一个查找函数find(查找栈内是否有某元素,返回对应位置。没有使用内置函数)
思路:
使用一个指针top,初始为0
依次查找popV中元素在pushV中是否存在,不存在直接返回False
存在时,返回元素对应pushV中位置key,当key>=top时,删除pushV[key],此时如果key>0,则更新top = key-1 。否则top=0。
当pushV成为空栈时,返回True
代码如下,测试通过:
class Solution:
def IsPopOrder(self, pushV, popV):
# write code here
if not (pushV and popV and len(pushV) == len(popV)):
return False
i=0
top=0
while pushV:
key = self.find(pushV,popV[i])
if not (type(key) == int) :
return False
if key >= top :
del pushV[key]
if key>0:
top = key-1
else:
top = 0
i += 1
else:
return False
return True
def find(self,stack,node):
if not stack:
return False
for i in range(0,len(stack)):
if stack[i] == node :
return i
return False