From 009662f6350017914db18adcbf0cef8c1aa522d4 Mon Sep 17 00:00:00 2001 From: qiuxuewei Date: Fri, 26 Nov 2021 14:26:01 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=2020.=20=E6=9C=89=E6=95=88?= =?UTF-8?q?=E7=9A=84=E6=8B=AC=E5=8F=B7=20Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0020.有效的括号.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/problems/0020.有效的括号.md b/problems/0020.有效的括号.md index 57aa5a01..5f597a1a 100644 --- a/problems/0020.有效的括号.md +++ b/problems/0020.有效的括号.md @@ -283,6 +283,29 @@ var isValid = function(s) { }; ``` +Swift +```swift +func isValid(_ s: String) -> Bool { + var stack = [String.Element]() + for ch in s { + if ch == "(" { + stack.append(")") + } else if ch == "{" { + stack.append("}") + } else if ch == "[" { + stack.append("]") + } else { + let top = stack.last + if ch == top { + stack.removeLast() + } else { + return false + } + } + } + return stack.isEmpty +} +``` -----------------------