力扣(LeetCode)159. 至多包含两个不同字符的最长子串(2022.06.08)

力扣(LeetCode)159. 至多包含两个不同字符的最长子串(2022.06.08),第1张

给定一个字符串 s ,找出 至多 包含两个不同字符的最长子串 t ,并返回该子串的长度。

示例 1:

输入: “eceba”
输出: 3
解释: t 是 “ece”,长度为3。
示例 2:

输入: “ccaabbb”
输出: 5
解释: t 是 “aabbb”,长度为5。
通过次数23,666提交次数42,557

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/longest-substring-with-at-most-two-distinct-characters

方法一:滑动窗口

C++提交内容:

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;
    }
};

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1354301.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-14
下一篇 2022-06-14

发表评论

登录后才能评论

评论列表(0条)

保存