From ed1b1d2d39b080e7e45c2a92cb11e631f7ec5d94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9E=81=E5=AE=A2=E5=AD=A6=E4=BC=9F?= Date: Fri, 3 Sep 2021 13:25:14 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20383.=20=E8=B5=8E=E9=87=91?= =?UTF-8?q?=E4=BF=A1=20Swift=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0383.赎金信.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/problems/0383.赎金信.md b/problems/0383.赎金信.md index 64503cef..18b1de9b 100644 --- a/problems/0383.赎金信.md +++ b/problems/0383.赎金信.md @@ -266,6 +266,28 @@ var canConstruct = function(ransomNote, magazine) { }; ``` +Swift: +```swift +func canConstruct(_ ransomNote: String, _ magazine: String) -> Bool { + var record = Array(repeating: 0, count: 26); + let aUnicodeScalarValue = "a".unicodeScalars.first!.value + for unicodeScalar in magazine.unicodeScalars { + // 通过record 记录 magazine 里各个字符出现的次数 + let idx: Int = Int(unicodeScalar.value - aUnicodeScalarValue) + record[idx] += 1 + } + for unicodeScalar in ransomNote.unicodeScalars { + // 遍历 ransomNote,在record里对应的字符个数做 -- 操作 + let idx: Int = Int(unicodeScalar.value - aUnicodeScalarValue) + record[idx] -= 1 + // 如果小于零说明在magazine没有 + if record[idx] < 0 { + return false + } + } + return true +} +``` -----------------------