forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestSubstringKDistinct.java
More file actions
42 lines (33 loc) · 1.08 KB
/
LongestSubstringKDistinct.java
File metadata and controls
42 lines (33 loc) · 1.08 KB
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
package com.thealgorithms.strings;
import java.util.HashMap;
public class LongestSubstringKDistinct {
/**
* Returns the length of the longest substring that contains
* at most k distinct characters.
*
* Sliding Window + HashMap
* Time Complexity: O(n)
* Space Complexity: O(k)
*/
public static int longestSubstringKDistinct(String s, int k) {
if (k == 0 || s == null || s.isEmpty()) {
return 0;
}
int left = 0, maxLen = 0;
HashMap<Character, Integer> map = new HashMap<>();
for (int right = 0; right < s.length(); right++) {
char ch = s.charAt(right);
map.put(ch, map.getOrDefault(ch, 0) + 1);
while (map.size() > k) {
char leftChar = s.charAt(left);
map.put(leftChar, map.get(leftChar) - 1);
if (map.get(leftChar) == 0) {
map.remove(leftChar);
}
left++;
}
maxLen = Math.max(maxLen, right - left + 1);
}
return maxLen;
}
}