# 340 Longest Substring with At Most K Distinct Characters

## 340. [Longest Substring with At Most K Distinct Characters](https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/description/)

## 1. Question

Given a string, find the length of the longest substring T that contains at mostkdistinct characters.

For example, Given s =`“eceba”`and k = 2,

T is "ece" which its length is 3.

## 2. Implementation

**(1) Two Pointer + Hash**

```java
class Solution {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        if (s.length() <= k) {
            return s.length();
        }

        int maxLen = 0, start = 0, end = 0, count = 0;
        int[] map = new int[256];

        while (end < s.length()) {
            if (map[s.charAt(end)] == 0) {
                ++count;
            }
            ++map[s.charAt(end)];
            ++end;

            while (count > k) {
                if (map[s.charAt(start)] == 1) {
                    --count;
                }
                --map[s.charAt(start)];
                ++start;
            }
            maxLen = Math.max(maxLen, end - start);
        }
        return maxLen;
    }
}
```

## 3. Time & Space Complexity

**Two Pointer + Hash:** 时间复杂度O(n), 空间复杂度O(1)
