Share Simple Java Solution


  • 0
    M
            public int lengthOfLongestSubstringKDistinct(String s, int k) {
                if (s == null || k <= 0) return 0;
    		if (s.length() <= k) return s.length();
    		int n = s.length();
    		Map<Character, Integer> map = new HashMap<>();
    		int max = 0;
    		int i = 0, j = 0;
    		while (j < n) {			
    			map.put(s.charAt(j), j);
    			if (map.size() <= k) {
    				max = Math.max(max, j - i + 1);
    				++j;
    				continue;
    			} else {
    				while (i <= j && map.size() > k) {
    					char c = s.charAt(i);
    					if (map.containsKey(c) && map.get(c) == i) {
    						map.remove(c);
    					}
    					++i;
    				}
    			}
    		}
    		return max;
            }
    

Log in to reply
 

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