[Swift Weekly Contest 112]LeetCode946. 验证栈序列 | Validate Stack Sequences

[Swift Weekly Contest 112]LeetCode946. 验证栈序列 | Validate Stack Sequences,第1张

概述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:

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:

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

给定 pushed 和 popped 两个序列,只有当它们可能是在最初空栈上进行的推入 push 和d出 pop *** 作序列的结果时,返回 true;否则,返回 false 。

示例 1:

输入:pushed = [1,popped = [4,1]输出:true解释:我们可以按以下顺序执行:push(1),pop() -> 1

示例 2:

输入:pushed = [1,2]输出:false解释:1 不能在 2 之前d出。

 提示:

0 <= pushed.length == popped.length <= 1000 0 <= pushed[i],popped[i] < 1000 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 += 112             }13         }14         return s.isEmpty() && j == popped.count15     }16 }17 18 public struct Stack<T> {19     20     // 泛型数组:用于存储数据元素21     fileprivate var stack: [T] 22 23     // 返回堆栈中元素的个数24     public var count: Int {25         return stack.count26     }27     28     /// 构造函数:创建一个空的堆栈29     public init() {30         stack = [T]()31     }32     33     // 检查堆栈是否为空34     // - returns: 如果堆栈为空,则返回true,否则返回false35     public func isEmpty() -> Bool {36         return stack.isEmpty37     }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 }
总结

以上是内存溢出为你收集整理的[Swift Weekly Contest 112]LeetCode946. 验证栈序列 | Validate Stack Sequences全部内容,希望文章能够帮你解决[Swift Weekly Contest 112]LeetCode946. 验证栈序列 | Validate Stack Sequences所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1022380.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存