当前位置:网站首页>Leetcode 159 Longest substring containing at most two different characters (2022.06.08)

Leetcode 159 Longest substring containing at most two different characters (2022.06.08)

2022-06-09 11:27:00 ChaoYue_ miku

Given a string s , find at most The longest substring containing two different characters t , And returns the length of the substring .

Example 1:

Input : “eceba”
Output : 3
explain : t yes “ece”, The length is 3.
Example 2:

Input : “ccaabbb”
Output : 5
explain : t yes “aabbb”, The length is 5.
Pass times 23,666 Submit the number 42,557

source : Power button (LeetCode)
link :https://leetcode.cn/problems/longest-substring-with-at-most-two-distinct-characters

Method 1 : The sliding window

C++ Submission :

class Solution {
    
public:
    int lengthOfLongestSubstringTwoDistinct(string s) {
    
        int len = s.size();
        int l = 0, r = 0, ch = 0, ans = 0;
        unordered_map<char, int> window;
        while(r < len){
    
            char ch1 = s[r];
            if(window[ch1] == 0){
    
                ch++;
            }
            window[ch1]++;
            while(ch > 2){
    
                char ch2 = s[l++];
                window[ch2]--;
                if(window[ch2] == 0){
    
                    ch--;
                }
            }
            ans = max(ans, r - l + 1);
            r++;
        }
        return ans;
    }
};
原网站

版权声明
本文为[ChaoYue_ miku]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091036549282.html

随机推荐