-
Notifications
You must be signed in to change notification settings - Fork 894
/
Copy pathLongestSubstringMostKDistinctCharacters.swift
45 lines (38 loc) · 1.38 KB
/
LongestSubstringMostKDistinctCharacters.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
/**
* Question Link: https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/
* Primary idea: Slding window, use dictionary to check substring is valid or not, and
note to handle the end of string edge case
*
* Note: k may be invalid, mention that with interviewer
* Time Complexity: O(n), Space Complexity: O(n)
*
*/
class LongestSubstringMostKDistinctCharacters {
func lengthOfLongestSubstringKDistinct(_ s: String, _ k: Int) -> Int {
guard k > 0 else {
return 0
}
var charFreqMap = [Character: Int](), left = 0, res = 0
let s = Array(s)
for (i, char) in s.enumerated() {
if let freq = charFreqMap[char] {
charFreqMap[char] = freq + 1
} else {
// update res
res = max(i - left, res)
// move left and window
while charFreqMap.count == k {
if let leftFreq = charFreqMap[s[left]] {
charFreqMap[s[left]] = leftFreq == 1 ? nil : leftFreq - 1
left += 1
} else {
fatalError()
}
}
// update window for current char
charFreqMap[char] = 1
}
}
return max(res, s.count - left)
}
}