Posted on 2023-04-13 16:54
Uriel 阅读(33)
评论(0) 编辑 收藏 引用 所属分类:
模拟 、
闲来无事重切Leet Code 、
大水题
给出push和pop栈的数字序列,问是否来自合法的栈操作,简单模拟
1 #946
2 #Runtime: 57 ms (Beats 23.66%)
3 #Memory: 13.6 MB (Beats 67.74%)
4
5 class Solution(object):
6 def validateStackSequences(self, pushed, popped):
7 """
8 :type pushed: List[int]
9 :type popped: List[int]
10 :rtype: bool
11 """
12 stk = []
13 p1, p2 = 0, 0
14 while p1 < len(pushed) or p2 < len(popped):
15 if stk and p2 < len(popped) and stk[-1] == popped[p2]:
16 stk.pop()
17 p2 += 1
18 elif p1 < len(pushed):
19 stk.append(pushed[p1])
20 p1 += 1
21 else:
22 return False
23 if p1 == len(pushed) and p2 == len(popped):
24 return True
25 return False