Skip to content

Commit 773c360

Browse files
committed
Longest Substring with at most K Distinct characters
1 parent 2e32eb2 commit 773c360

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package Review_2024;
2+
3+
import java.util.Map;
4+
import java.util.HashMap;
5+
6+
public class LongestSubstringWKDistinctChars {
7+
8+
public int longestSubstringWKDistinctChars(String s, int k) {
9+
if (s == null || s.length() == 0 || k == 0) {
10+
return 0;
11+
}
12+
13+
Map<Character, Integer> charMap = new HashMap<>();
14+
int left = 0;
15+
int maxLen = 0;
16+
17+
for (int right = 0; right < s.length(); right++) {
18+
char c = s.charAt(right);
19+
charMap.put(c, right);
20+
21+
while (charMap.size() > k) {
22+
char lc = s.charAt(left);
23+
if (charMap.get(lc) == left) {
24+
charMap.remove(lc);
25+
}
26+
left++;
27+
}
28+
maxLen = Math.max(maxLen, right - left + 1);
29+
}
30+
return maxLen;
31+
}
32+
33+
public static void main(String[] args) {
34+
LongestSubstringWKDistinctChars ls = new LongestSubstringWKDistinctChars();
35+
String s = "eceba";
36+
int k = 2;
37+
int len = ls.longestSubstringWKDistinctChars(s, k);
38+
System.out.println(len);
39+
}
40+
}

0 commit comments

Comments
 (0)