1.题目描述
给定 pushed
和 popped
两个序列,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列的结果时,返回 true
;否则,返回 false
。
示例 1:
输入:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
输出:true
解释:我们可以按以下顺序执行:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
示例 2:
输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
输出:false
解释:1 不能在 2 之前弹出。
提示:
0 <= pushed.length == popped.length <= 1000
0 <= pushed[i], popped[i] < 1000
pushed 是 popped 的排列。
2.解题思路
(1)方法1
刚接触到题目时,使用了一种完全非常规的判断方法(且相当不经济) :)
以popped
循环遍历,查找每一个popped
里的数字在pushed
中的索引,由栈属性可知,新弹出的数字是栈顶元素,有三种情况,1.新加入的数字(在pushed
当前数字中的右侧),此时存储改变后的左侧第一位数字,同时考虑到该数字是否已经弹出。2.当前数字的左侧第一位数字(在pushed
当前数字中的左侧第一位),将left
变量继续左移到合法位置。3.当前数字左侧非第一位数字,因该题目中所有数字都只出现一次,故该情况不合法。
(2)方法2
按照栈的思想,创建一个新的数组cur
,从pushed
中循环遍历把每个元素加入新的数组cur
,每次加入新元素都检查cur
最后一位是否是popped
的第一位元素,若是,在cur
剔除最后一位元素,并把popped
指针向右移动一位,最后检查popped
是否遍历完全,即可判断是否为合法栈顺序。
3.Python代码
(1)方法1
class Solution:
def validateStackSequences(self, pushed, popped):
"""
:type pushed: List[int]
:type popped: List[int]
:rtype: bool
"""
if pushed==[]:
return True
i=0
curr=pushed.index(popped[i])
left=curr-1
push_rest=pushed[:]
push_rest.remove(popped[i])
while i<len(pushed)-1:
i+=1
push_rest.remove(popped[i])
curr=pushed.index(popped[i])
if curr==left:#说明向左移动
left=left-1
while pushed[left] not in push_rest and left>0:
left=left-1
continue
elif curr>left:#说明向右移动
left=curr-1
while pushed[left] not in push_rest and left>0:
left=left-1
continue
else:#说明不合格
return(False)
return(True)
(2)方法2
class Solution:
def validateStackSequences(self, pushed, popped):
"""
:type pushed: List[int]
:type popped: List[int]
:rtype: bool
"""
cur = []
i = 0
for x in pushed:
cur.append(x)
while cur and cur[-1] == popped[i]:
i += 1
cur.pop()
return (i == len(popped))