1010class MinimumWindowSubstring {
1111
1212 func minWindow( _ s: String , _ t: String ) -> String {
13- var tFreqs = Dictionary ( t. map { ( $0, 1 ) } , uniquingKeysWith: + ) , count = 0
14- var sChars = Array ( s) , res = " " , start = 0
13+ let sChars = Array ( s) , tChars = Array ( t)
14+ var tFreq = Dictionary ( tChars. map { ( $0, 1 ) } , uniquingKeysWith: + )
15+ var left = 0 , shortestLen = Int . max, start = 0 , matters = 0
1516
1617 for (i, sChar) in sChars. enumerated ( ) {
17- guard let freq = tFreqs [ sChar] else {
18+ guard let sCharFreq = tFreq [ sChar] else {
1819 continue
1920 }
2021
21- tFreqs [ sChar] = freq - 1
22+ tFreq [ sChar] = sCharFreq - 1
2223
23- if freq > 0 {
24- count += 1
24+ if sCharFreq > 0 {
25+ matters += 1
2526 }
2627
27- while count == t. count {
28- // jump over redundants
29- guard let startFreq = tFreqs [ sChars [ start] ] else {
30- start += 1
28+ while matters == tChars. count {
29+ guard let leftFreq = tFreq [ sChars [ left] ] else {
30+ left += 1
3131 continue
3232 }
3333
34- tFreqs [ sChars [ start ] ] = startFreq + 1
35-
36- if startFreq == 0 {
37- // update res
38- if res . isEmpty || res . count > i - start + 1 {
39- res = String ( sChars [ start ... i ] )
34+ if leftFreq == 0 {
35+ matters -= 1
36+
37+ if i - left + 1 < shortestLen {
38+ shortestLen = i - left + 1
39+ start = left
4040 }
4141
42- count -= 1
4342 }
4443
45- start += 1
46-
44+ tFreq [ sChars [ left ] ] = leftFreq + 1
45+ left += 1
4746 }
4847 }
4948
50- return res
49+ return shortestLen == Int . max ? " " : String ( sChars [ start ..< start + shortestLen ] )
5150 }
5251}
0 commit comments