原题链接在这里:https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/
题目:
Given a string, find the length of the longest substring T that contains at most k distinct characters.
For example, Given s = “eceba”
and k = 2,
T is “ece” which its length is 3.
题解:
类似Longest Substring with At Most Two Distinct Characters.
2变成k即可.
Time Complexity: O(n), n = s.length(). Space: O(1), map size.
AC Java:
public class Solution {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
int res = 0;
int [] map = new int[256];
int walker = 0;
int runner = 0;
int count = 0;
while(runner < s.length()){
if(map[s.charAt(runner++)]++ == 0){
count++;
}
while(count > k){
if(map[s.charAt(walker++)]-- == 1){
count--;
}
}
res = Math.max(res, runner - walker);
}
return res;
}
}