Last active
December 30, 2018 20:00
-
-
Save azimbabu/8860ef9752404cc3d90c7afb1a3266f2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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