Untitled

 avatar
unknown
plain_text
a month ago
2.2 kB
3
Indexable
public class LongestSubstringKDistinct {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        if (s == null || s.length() == 0 || k == 0) {
            return 0;
        }

        Map<Character, Integer> map = new HashMap<>();
        int i = 0, j = 0, maxLength = 0;

        while (j < s.length()) {
            // Expand the window by including the current character
            char c = s.charAt(j);
            map.put(c, map.getOrDefault(c, 0) + 1);

            // Shrink the window until there are at most k distinct characters
            while (map.size() > k) {
                char leftChar = s.charAt(i);
                map.put(leftChar, map.get(leftChar) - 1);
                if (map.get(leftChar) == 0) {
                    map.remove(leftChar);
                }
                i++;
            }

            // Update the maximum length of the substring
            maxLength = Math.max(maxLength, j - i + 1);

            // Move the right pointer
            j++;
        }

        return maxLength;
    }
}


public class LongestSubstringKDistinct {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        if (s == null || s.length() == 0 || k == 0) {
            return 0;
        }

        Map<Character, Integer> map = new HashMap<>();
        int i = 0, j = 0, maxLength = 0;

        while (j < s.length()) {
            // Expand the window by including the current character
            char c = s.charAt(j);
            map.put(c, map.getOrDefault(c, 0) + 1);

            // Shrink the window by 1
            if (map.size() > k) {
                char leftChar = s.charAt(i);
                map.put(leftChar, map.get(leftChar) - 1);
                if (map.get(leftChar) == 0) {
                    map.remove(leftChar);
                }
                i++;
            }

            // Update the maximum length of the substring if <=k
            if(map.size() <= k)  
              maxLength = Math.max(maxLength, j - i + 1);

            // Move the right pointer
            j++;
        }

        return maxLength;
    }
}
Leave a Comment