|
| 1 | +class Solution { |
| 2 | + func minWindow(_ s: String, _ t: String) -> String { |
| 3 | + if t.isEmpty { return "" } |
| 4 | + |
| 5 | + var countT: [Character : Int] = [:] |
| 6 | + var window: [Character : Int] = [:] |
| 7 | + let stringArray = Array(s) |
| 8 | + |
| 9 | + // Storing each char and its count in hashMap |
| 10 | + for char in t { |
| 11 | + countT[char, default: 0] += 1 |
| 12 | + } |
| 13 | + |
| 14 | + var have = 0 |
| 15 | + let need = t.count |
| 16 | + var resultRange = (-1, -1) |
| 17 | + var resultLength = Int.max |
| 18 | + var l = 0 |
| 19 | + |
| 20 | + for r in 0...s.count - 1 { |
| 21 | + let char = stringArray[r] |
| 22 | + window[char, default: 0] += 1 |
| 23 | + |
| 24 | + if countT.contains(where: { $0.key == char }) && window[char] == countT[char] { |
| 25 | + // for the case of repeated characters "have" should be increased by count, not by 1 |
| 26 | + have += countT[char, default: 0] |
| 27 | + } |
| 28 | + |
| 29 | + while have == need { |
| 30 | + // update result |
| 31 | + if r - l + 1 < resultLength { |
| 32 | + resultRange = (l, r) |
| 33 | + resultLength = r - l + 1 |
| 34 | + } |
| 35 | + // pop from left of the window |
| 36 | + window[stringArray[l], default: 0] -= 1 |
| 37 | + |
| 38 | + if countT.contains(where: { $0.key == stringArray[l] }) |
| 39 | + && window[stringArray[l], default: 0] < countT[stringArray[l], default: 0] { |
| 40 | + //subtract all count, because in second iteration will be added total count of char. |
| 41 | + have -= countT[stringArray[l], default: 0] |
| 42 | + } |
| 43 | + |
| 44 | + l += 1 |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + guard resultLength != Int.max else { return "" } |
| 49 | + return String(stringArray[resultRange.0...resultRange.1]) |
| 50 | + } |
| 51 | +} |
0 commit comments