8 line solution using substring template

  • 1
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
            int [] arr = new int[128];
            int counter=0,end=0,begin=0,d=0;
                if(arr[s.charAt(end++)]++ == 0) counter++;
                while(counter>k) if(arr[s.charAt(begin++)]-- ==1) counter--;
                d = Math.max(d,end-begin);
            return d;

Log in to reply

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