Given a string s, find the length of the longest substring T that contains at most k distinct characters.

For example, Given s ="eceba",k = 3, T is"eceb"which its length is4.

Solution: 用hashmap记录出现过的字母和次数,当hashmap.size() > k时,一直删之前的字母,直到hashmap.size() == k,update max

    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        if(s == null || s.length() == 0 || k == 0){
            return 0;
        }
        int max = 0, i = 0, j = 0;
        Map<Character, Integer> hashmap = new HashMap<Character, Integer>();
        while (j < s.length()) {
            char c = s.charAt(j);
            hashmap.put(c, hashmap.getOrDefault(c, 0) + 1);
            while (hashmap.size() > k) {
                char c2 = s.charAt(i);
                if (hashmap.get(c2) == 1) {
                    hashmap.remove(c2);
                } else {
                    hashmap.put(c2, hashmap.get(c2) - 1);
                }
                i++;
            }
            max = Math.max(max, j - i + 1);    
            j++;
        }
        return max;
    }

results matching ""

    No results matching ""