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