Java two pointers - one loop


  • 0
    D
    public class Solution {
        public int lengthOfLongestSubstringKDistinct(String s, int k) {
            int[] table = new int[128];
            int count = 0;
            int n = s.length();
            if (n <= k)
                return n;
            if (k <= 0)
                return 0;
            int i = 0, j = 0;
            int max = 0;
            while (j < n && i <= j) {
                char c = s.charAt(j);
                if (count == k && table[c] == 0) { // increase i
                    char d = s.charAt(i);
                    table[d] --;
                    if (table[d] == 0)
                        count--;
                    i++;
                } else { // increase j
                    if (table[c] == 0)
                        count ++;
                    table[c]++;
                    j++;
                    max = Math.max(max, j - i);
                }
            }
            return max;
        }
    }
    

Log in to reply
 

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