-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestSubstringwithKDistinctCharacters.java
More file actions
34 lines (30 loc) · 1.53 KB
/
LongestSubstringwithKDistinctCharacters.java
File metadata and controls
34 lines (30 loc) · 1.53 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
import java.util.*;
class LongestSubstringKDistinct {
public static int findLength(String str, int k) {
if (str == null || str.length() == 0 || str.length() < k)
throw new IllegalArgumentException();
int windowStart = 0, maxLength = 0;
Map<Character, Integer> charFrequencyMap = new HashMap<>();
// in the following loop we'll try to extend the range [windowStart, windowEnd]
for (int windowEnd = 0; windowEnd < str.length(); windowEnd++) {
char rightChar = str.charAt(windowEnd);
charFrequencyMap.put(rightChar, charFrequencyMap.getOrDefault(rightChar, 0) + 1);
// shrink the sliding window, until we are left with 'k' distinct characters in the frequency map
while (charFrequencyMap.size() > k) {
char leftChar = str.charAt(windowStart);
charFrequencyMap.put(leftChar, charFrequencyMap.get(leftChar) - 1);
if (charFrequencyMap.get(leftChar) == 0) {
charFrequencyMap.remove(leftChar);
}
windowStart++; // shrink the window
}
maxLength = Math.max(maxLength, windowEnd - windowStart + 1); // remember the maximum length so far
}
return maxLength;
}
public static void main(String[] args) {
System.out.println("Length of the longest substring: " + LongestSubstringKDistinct.findLength("araaci", 2));
System.out.println("Length of the longest substring: " + LongestSubstringKDistinct.findLength("araaci", 1));
System.out.println("Length of the longest substring: " + LongestSubstringKDistinct.findLength("cbbebi", 3));
}
}