File tree Expand file tree Collapse file tree 1 file changed +22
-0
lines changed Expand file tree Collapse file tree 1 file changed +22
-0
lines changed Original file line number Diff line number Diff line change @@ -266,6 +266,28 @@ var canConstruct = function(ransomNote, magazine) {
266
266
};
267
267
```
268
268
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
+ ```
269
291
270
292
271
293
-----------------------
You can’t perform that action at this time.
0 commit comments