9-Lines 6-ms 2-Pointer Solution


  • 0
    O
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
            int[] b = new int[128];
            char[] c = s.toCharArray();
            int maxl = 0, len = c.length;
            
            for (int i = 0, j = 0, d = 0; i < len; i++) {
                if (b[c[i]]++ == 0) d++;
                while (d > k) if (--b[c[j++]] == 0) d--;
                if (i - j + 1 > maxl) maxl = i - j + 1;
            }
            return maxl;
        }

Log in to reply
 

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