Skip to content

Instantly share code, notes, and snippets.

@azimbabu
Last active December 30, 2018 20:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azimbabu/8860ef9752404cc3d90c7afb1a3266f2 to your computer and use it in GitHub Desktop.
Save azimbabu/8860ef9752404cc3d90c7afb1a3266f2 to your computer and use it in GitHub Desktop.
public int lengthOfLongestSubstringKDistinct(String str, int k) {
int maxLength = 0;
int distinct = 0;
int[] charCounts = new int[256];
for (int left = 0, right = 0; right < str.length(); right++) {
char rightChar = str.charAt(right);
if (charCounts[rightChar] == 0) {
distinct++;
}
charCounts[rightChar]++;
while (distinct > k) {
char leftChar = str.charAt(left);
charCounts[leftChar]--;
if (charCounts[leftChar] == 0) {
distinct--;
}
left++;
}
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}
public int lengthOfLongestSubstringKDistinct2(String str, int k) {
int maxLength = 0;
Map<Character, Integer> charCounts = new HashMap<>();
for (int left=0, right=0; right < str.length(); right++) {
char rightChar = str.charAt(right);
charCounts.put(rightChar, charCounts.getOrDefault(rightChar, 0) + 1);
while (charCounts.size() > k) {
char leftChar = str.charAt(left);
charCounts.put(leftChar, charCounts.get(leftChar) - 1);
if (charCounts.get(leftChar) == 0) {
charCounts.remove(leftChar);
}
left++;
}
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment