340. Longest Substring with At Most K Distinct Characters

把上题的2换成k即可

public int lengthOfLongestSubstringKDistinct(String s, int k) {
    if (s == null || s.length() == 0 || k == 0) {
        return 0;
    }
     
    char[] sArr = s.toCharArray();
     
    int[] hash = new int[256];
     
    int l = 0, count = 0, result = 1;
    for (int r = 0; r < sArr.length; ++r) {
        hash[sArr[r]]++;
         
        if (hash[sArr[r]] == 1) {
            count++;
        }
         
        while (count > k) {
            hash[sArr[l]]--;
 
            if (hash[sArr[l]] == 0) {
                count--;
            }
 
            l++;
        }
         
        result = Math.max(result, r - l + 1);
    }
     
    return result;
}

 

上一篇:Java中List去重(转载)


下一篇:distinct