340. Longest Substring with At Most K Distinct Characters

sliding window with hashmap

public class Solution {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        Map<Character, Integer> map = new HashMap<>();

        int result = 0;
        int num = 0;
        int start = 0;

        for (int i = 0; i < s.length(); ++i) {
            if (!map.containsKey(s.charAt(i))) {
                map.put(s.charAt(i), 1);
                num++;
            } else {
                map.put(s.charAt(i), map.get(s.charAt(i)) + 1);
            }

            while (num > k) {
                if (map.get(s.charAt(start)) == 1) {
                    map.remove(s.charAt(start));
                    num--;
                } else {
                    map.put(s.charAt(start), map.get(s.charAt(start)) - 1);
                }
                start++;
            }

            result = Math.max(result, i - start + 1);

        }


        return result;
    }
}

results matching ""

    No results matching ""