Skip to content

Commit 4e36237

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 340_Longest_Substring_with_At_Most_K_Distinct_Characters.java
1 parent 1ece5db commit 4e36237

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
public int lengthOfLongestSubstringKDistinct(String s, int k) {
3+
if (s == null || s.length() == 0) {
4+
return 0;
5+
}
6+
7+
int result = 0, distinctNums = 0;
8+
int[] map = new int[256];
9+
10+
for (int i = 0, j = 0; j < s.length(); j++) {
11+
if (map[s.charAt(j)]++ == 0) {
12+
distinctNums++;
13+
}
14+
15+
while (distinctNums > k) {
16+
if (--map[s.charAt(i)] == 0) {
17+
distinctNums--;
18+
}
19+
++i;
20+
}
21+
22+
result = Math.max(result, j - i + 1);
23+
}
24+
25+
return result;
26+
}
27+
}

0 commit comments

Comments
 (0)