Uriel's Corner

Research Associate @ Harvard University / Research Interests: Computer Vision, Biomedical Image Analysis, Machine Learning
posts - 0, comments - 50, trackbacks - 0, articles - 594
给出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

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理