LeetCode algorithm_C++ - the longest substring containing at most two different characters

Given a string s, please find the longest substring containing at most two different characters and return the length of the substring.

Example 1:
Input: s = "eceba"
Output: 3
Explanation: The substring that meets the requirements of the question is "ece", with a length of 3.

Example 2:
Input: s = "ccaabbb"
Output: 5
Explanation: The substring that meets the requirements of the question is "aabbb" with a length of 5.

    int lengthOfLongestSubstringTwoDistinct(string s) {
    
    
        int len = s.size();
        int i=0, j=0;
        int num = 1;
        char arr[130] = {
    
    0};
        int count = 0; 
        while(j < len){
    
    
            if(arr[s[j++]]++ == 0) count++;
            if(count <= 2) num = max(num,j-i);
            else{
    
    
                while(count > 2){
    
    
                    if(arr[s[i++]]-- == 1) count--;
                }          
            }
        }
        return num;
    }

Guess you like

Origin blog.csdn.net/weixin_43945471/article/details/132724113