Skip to content

Commit ed1b1d2

Browse files
author
极客学伟
committed
添加 383. 赎金信 Swift版本
1 parent 8b1454e commit ed1b1d2

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

problems/0383.赎金信.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,28 @@ var canConstruct = function(ransomNote, magazine) {
266266
};
267267
```
268268

269+
Swift:
270+
```swift
271+
func canConstruct(_ ransomNote: String, _ magazine: String) -> Bool {
272+
var record = Array(repeating: 0, count: 26);
273+
let aUnicodeScalarValue = "a".unicodeScalars.first!.value
274+
for unicodeScalar in magazine.unicodeScalars {
275+
// 通过record 记录 magazine 里各个字符出现的次数
276+
let idx: Int = Int(unicodeScalar.value - aUnicodeScalarValue)
277+
record[idx] += 1
278+
}
279+
for unicodeScalar in ransomNote.unicodeScalars {
280+
// 遍历 ransomNote,在record里对应的字符个数做 -- 操作
281+
let idx: Int = Int(unicodeScalar.value - aUnicodeScalarValue)
282+
record[idx] -= 1
283+
// 如果小于零说明在magazine没有
284+
if record[idx] < 0 {
285+
return false
286+
}
287+
}
288+
return true
289+
}
290+
```
269291

270292

271293
-----------------------

0 commit comments

Comments
 (0)