File tree 2 files changed +97
-0
lines changed
lcof2/剑指 Offer II 017. 含有所有字符的最短字符串
2 files changed +97
-0
lines changed Original file line number Diff line number Diff line change @@ -326,6 +326,57 @@ func minWindow(s string, t string) string {
326
326
}
327
327
```
328
328
329
+ #### Swift
330
+
331
+ ``` swift
332
+ class Solution {
333
+ func minWindow (_ s : String , _ t : String ) -> String {
334
+ let m = s.count , n = t.count
335
+ if n > m {
336
+ return " "
337
+ }
338
+
339
+ var need = [Character : Int ]()
340
+ var window = [Character : Int ]()
341
+
342
+ for ch in t {
343
+ need[ch, default : 0 ] += 1
344
+ }
345
+
346
+ let sArray = Array (s)
347
+ var start = 0 , minLen = Int .max
348
+ var left = 0 , right = 0
349
+
350
+ while right < m {
351
+ let ch = sArray[right]
352
+ window[ch, default : 0 ] += 1
353
+ right += 1
354
+
355
+ while check (need, window) {
356
+ if right - left < minLen {
357
+ minLen = right - left
358
+ start = left
359
+ }
360
+ let leftChar = sArray[left]
361
+ window[leftChar, default : 0 ] -= 1
362
+ left += 1
363
+ }
364
+ }
365
+
366
+ return minLen == Int .max ? " " : String (sArray[start..< start + minLen])
367
+ }
368
+
369
+ private func check (_ need : [Character : Int ], _ window : [Character : Int ]) -> Bool {
370
+ for (key, value) in need {
371
+ if window[key, default : 0 ] < value {
372
+ return false
373
+ }
374
+ }
375
+ return true
376
+ }
377
+ }
378
+ ```
379
+
329
380
<!-- tabs:end -->
330
381
331
382
<!-- solution:end -->
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ func minWindow( _ s: String , _ t: String ) -> String {
3
+ let m = s. count, n = t. count
4
+ if n > m {
5
+ return " "
6
+ }
7
+
8
+ var need = [ Character: Int] ( )
9
+ var window = [ Character: Int] ( )
10
+
11
+ for ch in t {
12
+ need [ ch, default: 0 ] += 1
13
+ }
14
+
15
+ let sArray = Array ( s)
16
+ var start = 0 , minLen = Int . max
17
+ var left = 0 , right = 0
18
+
19
+ while right < m {
20
+ let ch = sArray [ right]
21
+ window [ ch, default: 0 ] += 1
22
+ right += 1
23
+
24
+ while check ( need, window) {
25
+ if right - left < minLen {
26
+ minLen = right - left
27
+ start = left
28
+ }
29
+ let leftChar = sArray [ left]
30
+ window [ leftChar, default: 0 ] -= 1
31
+ left += 1
32
+ }
33
+ }
34
+
35
+ return minLen == Int . max ? " " : String ( sArray [ start..< start + minLen] )
36
+ }
37
+
38
+ private func check( _ need: [ Character : Int ] , _ window: [ Character : Int ] ) -> Bool {
39
+ for (key, value) in need {
40
+ if window [ key, default: 0 ] < value {
41
+ return false
42
+ }
43
+ }
44
+ return true
45
+ }
46
+ }
You can’t perform that action at this time.
0 commit comments