340.至多包含K个不同字符的最长子串

【LeetCode刷题-滑动窗口】--340.至多包含K个不同字符的最长子串-LMLPHP

class Solution {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        int len = s.length();
        if(len <= k){
            return len;
        }
        //滑动窗口的左右指针
        int left = 0,right = 0;
        //定义一个哈希映射
        HashMap<Character,Integer> hashmap = new HashMap<Character,Integer>();

        int max_len = k;
        while(right < len){
            hashmap.put(s.charAt(right),right++);
            if(hashmap.size() == k + 1){
                int del_idx = Collections.min(hashmap.values());
                hashmap.remove(s.charAt(del_idx));
                left = del_idx + 1;
            }
            max_len = Math.max(max_len,right - left);
        }
        return max_len;
    }
}
11-17 12:51