Share my 5 ms solution


  • 0
    X

    basically using two pointer technique to maintain a sliding window

    public class Solution {
        public int lengthOfLongestSubstringKDistinct(String s, int k) {
            if (s == null || s.length() == 0) return 0;
            if (k >=  s.length()) return s.length();
            int[] freq = new int[256];
            char[] cha = s.toCharArray();
            int j = 0, max = k, count = 0; 
            for (int i = 0; i < cha.length; i++) {
                char c = cha[i];
                if (freq[c]++ == 0 && ++count > k) {
                    max = Math.max(max, i - j);
                    while (--freq[cha[j++]] != 0); 
                    count--;
                }
            } 
            return Math.max(s.length() - j, max);
        }
    }
    
    ''~~~

Log in to reply
 

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