微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[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,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,popped = [4,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,popped = [4,1]
输出:true
解释:我们可以按以下顺序执行:
push(1),pop() -> 1

示例 2:

输入:pushed = [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 }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐