1
1
/**
2
2
* Question Link: https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/
3
- * Primary idea: Slding window, use dictionary to check substring is valid or not, and
3
+ * Primary idea: Slding window. Use char freq map to check substring is valid or not, and
4
4
note to handle the end of string edge case
5
5
*
6
6
* Time Complexity: O(n), Space Complexity: O(n)
9
9
10
10
class LongestSubstringMostTwoDistinctCharacters {
11
11
func lengthOfLongestSubstringTwoDistinct( _ s: String ) -> Int {
12
- var start = 0 , longest = 0 , charFreq = [ Character : Int ] ( )
13
- let sChars = Array ( s)
14
-
15
- for (i, char) in sChars . enumerated ( ) {
16
- if let freq = charFreq [ char] {
17
- charFreq [ char] = freq + 1
12
+ var charFreqMap = [ Character : Int ] ( ) , left = 0 , res = 0
13
+ let s = Array ( s)
14
+
15
+ for (i, char) in s . enumerated ( ) {
16
+ if let freq = charFreqMap [ char] {
17
+ charFreqMap [ char] = freq + 1
18
18
} else {
19
- if charFreq. count == 2 {
20
- longest = max ( longest, i - start)
21
-
22
- while charFreq. count == 2 {
23
- let charStart = sChars [ start]
24
- charFreq [ charStart] ! -= 1
25
-
26
- if charFreq [ charStart] == 0 {
27
- charFreq [ charStart] = nil
28
- }
29
-
30
- start += 1
31
- }
19
+
20
+ // update res
21
+ res = max ( i - left, res)
22
+
23
+ // move left and window
24
+ while charFreqMap. count == 2 {
25
+ if let leftFreq = charFreqMap [ s [ left] ] {
26
+ charFreqMap [ s [ left] ] = leftFreq == 1 ? nil : leftFreq - 1
27
+ left += 1
28
+ } else {
29
+ fatalError ( )
30
+ }
32
31
}
33
-
34
- charFreq [ char] = 1
32
+
33
+ // update window for current char
34
+ charFreqMap [ char] = 1
35
35
}
36
36
}
37
-
38
- return max ( longest , sChars . count - start )
37
+
38
+ return max ( res , s . count - left )
39
39
}
40
- }
40
+ }
0 commit comments