输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。
1. 0<=pushV.length == popV.length <=1000
2. -1000<=pushV[i]<=1000
3. pushV 的所有数字均不相同
[1,2,3,4,5],[4,5,3,2,1]
true
可以通过push(1)=>push(2)=>push(3)=>push(4)=>pop()=>push(5)=>pop()=>pop()=>pop()=>pop() 这样的顺序得到[4,5,3,2,1]这个序列,返回true
[1,2,3,4,5],[4,3,5,1,2]
false
由于是[1,2,3,4,5]的压入顺序,[4,3,5,1,2]的弹出顺序,要求4,3,5必须在1,2前压入,且1,2不能弹出,但是这样压入的顺序,1又不能在2之前弹出,所以无法形成的,返回false
class Solution: def IsPopOrder(self , pushV: List[int], popV: List[int]) -> bool: n = len(pushV) j = 0 s = [] for i in range(n): while j < n and (len(s) == 0 or s[-1] != popV[i]): s.append(pushV[j]) j += 1 if s[-1] == popV[i]: s.pop() else: return False return True
class Solution: def IsPopOrder(self , pushV: List[int], popV: List[int]) -> bool: # write code here self.data = [] lens = len(pushV) for idx in range(lens): # 压盏 self.data.append(pushV[0]) pushV.remove(pushV[0]) # 如果 栈顶元素 和 popV 头元素一致则 pop while len(self.data) >= 1 and self.data[-1] == popV[0] : self.data = self.data[:-1] popV = popV[1:] return len(self.data) == 0
非递归,双指针
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param pushV int整型一维数组 # @param popV int整型一维数组 # @return bool布尔型 # class Solution: def IsPopOrder(self , pushV: List[int], popV: List[int]) -> bool: # write code here if len(pushV) == 0 and len(popV) == 0: return True pr_push = 0 pr_pop = 0 stack_size = len(pushV) t = [] while pr_push < stack_size and pr_pop < stack_size: size_t = len(t) if pushV[pr_push] == popV[pr_pop]: pr_push += 1 pr_pop += 1 continue if size_t > 0 and t[-1] == popV[pr_pop]: # pr_push += 1 pr_pop += 1 t.pop() continue t.append(pushV[pr_push]) pr_push += 1 while t: n_pop = t.pop() if n_pop != popV[pr_pop]: return False pr_pop +=1 return True
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param pushV int整型一维数组 # @param popV int整型一维数组 # @return bool布尔型 # class Solution: def __init__(self): self.stack = [] def IsPopOrder(self , pushV: List[int], popV: List[int]) -> bool: # write code here # 模拟压入和弹出的过程, 看最后是否都能够弹出 if not pushV&nbs***bsp;not popV&nbs***bsp;len(pushV) != len(popV): return False for ele in pushV: self.stack.append(ele) while self.stack and self.stack[-1] == popV[0]: self.stack.pop(-1) popV.pop(0) if not popV: return True return False
# -*- coding:utf-8 -*- class Solution: def IsPopOrder(self, pushV, popV): # write code here q=[] i,j=0,0 while j<len(popV): if len(q)==0&nbs***bsp;q[-1]!=popV[j]: #只能压入 if i==len(pushV): return False q.append(pushV[i]) i+=1 else: #弹出 q.pop() j+=1 return True