1. 程式人生 > >[Swift Weekly Contest 112]LeetCode946. 驗證棧序列 | Validate Stack Sequences

[Swift Weekly Contest 112]LeetCode946. 驗證棧序列 | Validate Stack Sequences

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 和 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 之前彈出。

 提示:

  1. 0 <= pushed.length == popped.length <= 1000
  2. 0 <= pushed[i], popped[i] < 1000
  3. pushed 是 popped 的排列。

72ms
 1 class Solution {
 2     func validateStackSequences(_ pushed: [Int], _ popped: [Int]) -> Bool {
 3         var s:Stack<Int> = Stack<Int>()
 4         var j:Int = 0
 5         for i in 0..<pushed.count
 6         {
 7             s.push(pushed[i])
 8             while (!s.isEmpty() && j < popped.count && s.getLast() == popped[j])
 9             {
10                 s.pop()
11                 j += 1
12             }
13         }
14         return s.isEmpty() && j == popped.count
15     }
16 }
17 
18 public struct Stack<T> {
19     
20     // 泛型陣列:用於儲存資料元素
21     fileprivate var stack: [T] 
22 
23     // 返回堆疊中元素的個數
24     public var count: Int {
25         return stack.count
26     }
27     
28     /// 建構函式:建立一個空的堆疊
29     public init() {
30         stack = [T]()
31     }
32     
33     // 檢查堆疊是否為空
34     // - returns: 如果堆疊為空,則返回true,否則返回false
35     public func isEmpty() -> Bool {
36         return stack.isEmpty
37     }
38     
39     // 入堆疊操作:將元素新增到堆疊的末尾
40     public mutating func push(_ element: T) {
41         stack.append(element)
42     }
43     
44     // 出堆疊操作:刪除並返回堆疊中的第一個元素
45     public mutating func pop() -> T? {
46         return stack.removeLast()
47     }
48  
49     // 返回堆疊中的第一個元素(不刪除)
50     public func getLast() -> T? {
51         return stack.last!
52     }
53 }