Skip to content

Instantly share code, notes, and snippets.

public int lengthOfLongestSubStringKDistinct(String s) {
int n = s.length();
int[] count = new int[256];
int i = 0, numDistinct = 0, ans = 0;
for (int j = 1; j < s.length(); j++) {
if (count[s.charAt(j)] == 0) {
numDistinct++;
}
count[s.charAt(j)]++;
while (numDistinct > 2) {
count[s.charAt(i)]--;
if (count[s.charAt(i)] == 0) {
numDistinct--;
}
i++;
}
ans = Math.max(ans, j - i + 1);
}
return ans;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment