forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LongestSubstringMostKDistinctCharacters.swift
45 lines (37 loc) · 1.46 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 {
var start = 0, longest = 0, charsFreq = [Character: Int]()
let sChars = Array(s)
guard k > 0 else {
return longest
}
for (i, char) in sChars.enumerated() {
if let freq = charsFreq[char] {
charsFreq[char] = freq + 1
} else {
if charsFreq.count == k {
longest = max(longest, i - start)
while charsFreq.count == k {
let charStart = sChars[start]
charsFreq[charStart]! -= 1
if charsFreq[charStart] == 0 {
charsFreq[charStart] = nil
}
start += 1
}
}
charsFreq[char] = 1
}
}
return max(longest, s.count - start)
}
}