Leetcode 340) Longest Substring with At Most K Distinct Characters
in Algorithms
My Answer
class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
int left =0; int right =0;
//Characters with values from 128 to 255 are the "Extended" character set.
int[] charInfo = new int[256];
int totChar =0; int max=0;
while(right < s.length()){
charInfo[s.charAt(right)]++;
if(charInfo[s.charAt(right)]==1){
totChar++;
}
while(totChar > k){
charInfo[s.charAt(left)]--;
if(charInfo[s.charAt(left)]==0){
totChar--;
}
left++;
}
if(max<right-left+1){
max= right-left+1;
}
right++;
}
return max;
}
}