Given a string, find the length of the longest substring T that contains at most k distinct characters.
Example 1:
Input: s = “eceba”, k = 2
Output: 3
Explanation: T is “ece” which its length is 3.
Example 2:
Input: s = “aa”, k = 1
Output: 2
Explanation: T is “aa” which its length is 2.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-with-at-most-k-distinct-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
int len = s.length();
if(len <= k) return len;
int ans = 0;
int[] count = new int[256];
int L=0, R=0;
int num=0;
while(R < len){
if(count[s.charAt(R)]==0) num++;
count[s.charAt(R)]++;
while(num > k){
count[s.charAt(L)]--;
if(count[s.charAt(L)]==0) --num;
L++;
}
R++;
ans = Math.max(ans, R - L);
}
return ans;
}
}