# 双指针，窗口类

* **这两题有一个 trick 和 Minimum Window Substring 非常像，就是维护一个 "curCount" 代表目前 (i,j) 之间 match 上的数量，而通过 hash\[] 的正负充当计数器的作用。**

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

```java
public class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        int maxSize = 0;
        int j = 0;
        int[] hash = new int[256];
        int distinctCount = 0;
        for(int i = 0; i < s.length(); i++){
            while(j < s.length()){
                if(distinctCount == 2 && hash[s.charAt(j)] == 0) break;

                if(hash[s.charAt(j)] == 0) distinctCount ++;
                hash[s.charAt(j++)]++;
            }
            if(j - i > maxSize){
                maxSize = j - i;
            }
            hash[s.charAt(i)]--;
            if(hash[s.charAt(i)] == 0) distinctCount --;
        }

        return maxSize;
    }
}
```

## [Longest Substring with At Most K Distinct Characters](https://github.com/mnmunknown/algorithm-notes/tree/3c03c403dea353c29bf5dc55966e338f3385a7ed/Longest%20Substring%20with%20At%20Most%20K%20Distinct%20Characters/README.md)

和上一题代码完全没有区别，只是把判断条件里面的 count 数字改一下而已。。

```java
public class Solution {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        int curCount = 0;
        int j = 0;
        int maxSize = 0;
        int[] hash = new int[256];
        for(int i = 0; i < s.length(); i++){
            while(j < s.length()){
                if(curCount == k && hash[s.charAt(j)] == 0) break;
                if(hash[s.charAt(j)] == 0) curCount ++;
                hash[s.charAt(j++)]++;
            }
            if(j - i > maxSize){
                maxSize = j - i;
            }

            hash[s.charAt(i)]--;
            if(hash[s.charAt(i)] == 0) curCount --;
        }

        return maxSize;
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://mnunknown.gitbook.io/algorithm-notes/two_pointers/615-_two_pointers-_shuang_zhi_zhen_ff0c_chuang_kou.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
