Skip to content

Commit 1eff3fb

Browse files
authored
Update and rename Hard/Longest Substring with At Most K Distinct Characters.java to Medium/Longest Substring with At Most K Distinct Characters.java
1 parent 38c9b25 commit 1eff3fb

File tree

2 files changed

+21
-22
lines changed

2 files changed

+21
-22
lines changed

Hard/Longest Substring with At Most K Distinct Characters.java

Lines changed: 0 additions & 22 deletions
This file was deleted.
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public int lengthOfLongestSubstringKDistinct(String s, int k) {
3+
Map<Character, Integer> map = new HashMap<>();
4+
int startIdx = 0;
5+
int endIdx = 0;
6+
int maxLength = 0;
7+
while (endIdx < s.length()) {
8+
map.put(s.charAt(endIdx), map.getOrDefault(s.charAt(endIdx), 0) + 1);
9+
endIdx++;
10+
while (startIdx < endIdx && map.size() > k) {
11+
map.put(s.charAt(startIdx), map.getOrDefault(s.charAt(startIdx), 0 ) - 1);
12+
if (map.get(s.charAt(startIdx)) == 0) {
13+
map.remove(s.charAt(startIdx));
14+
}
15+
startIdx++;
16+
}
17+
maxLength = Math.max(maxLength, endIdx - startIdx);
18+
}
19+
return maxLength;
20+
}
21+
}

0 commit comments

Comments
 (0)