1. 程式人生 > >【LeetCode】946. Validate Stack Sequences 解題報告(Python)

【LeetCode】946. Validate Stack Sequences 解題報告(Python)

作者: 負雪明燭
id: fuxuemingzhu
個人部落格: http://fuxuemingzhu.cn/


目錄

題目地址:https://leetcode.com/problems/minimum-increment-to-make-array-unique/description/

題目描述

Given two sequences pushed and popped with distinct values, return true

if and only if this could have been the result of a sequence of push and pop operations on an initially empty stack.

Example 1:

Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

Example 2:

Input: pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
Output: false
Explanation: 1 cannot be popped before 2.

Note:

  1. 0 <= pushed.length == popped.length <= 1000
  2. 0 <= pushed[i], popped[i] < 1000
  3. pushed is a permutation of popped.
  4. pushed and popped have distinct values.

題目大意

給出了一個棧的輸入數字,按照這個順序輸入到棧裡,能不能得到一個對應的棧的輸出序列。

解題方法

模擬過程

我使用的方法異常簡單粗暴,直接模擬這個過程。

題目已知所有的數字都是不同的。我們在模擬這個彈出的過程中,進行一個判斷,如果這個彈出的數字和棧頂數字是吻合的,那麼棧就要把已有的數字彈出來。如果棧是空的,或者棧頂數字和彈出的數字不等,那麼我們應該把pushed數字一直往裡放,直到相等為止。

最後,如果棧的入棧序列能得到這個出棧序列,那麼棧應該是空的。

class Solution(object):
    def validateStackSequences(self, pushed, popped):
        """
        :type pushed: List[int]
        :type popped: List[int]
        :rtype: bool
        """
        stack = []
        N = len(pushed)
        pi = 0
        for i in range(N):
            if stack and popped[i] == stack[-1]:
                stack.pop()
            else:
                while pi < N and pushed[pi] != popped[i]:
                    stack.append(pushed[pi])
                    pi += 1
                pi += 1
        return not stack

日期

2018 年 11 月 24 日 —— 週日開始!一週就過去了~