10 lines Java AC super simple solution same as 2 Distinct Characters

  • 0

    Actually this is exactly the same as "2 Distinct Characters" problem.

    Just replace 2 with k, and even the if() condition in the while (count > k) are the same. Because the map[start char] equals to whatever number before, it should be equal to 1 (after this step it will be equal to 0), and then we could deduct the count by 1..... So this question is totally equal to "2 Distinct Characters" problem~

    public int lengthOfLongestSubstringKDistinct(String s, int k) {
            int[] map = new int[128];
            int count = 0, start = 0, end = 0, d = 0;
            while (end < s.length()) {
                if (map[s.charAt(end++)]++ == 0) count++;
                while (count > k) if (map[s.charAt(start++)]-- == 1) count--;
                d = Math.max(d, end - start);
            return d;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.