Leetcode 159. 至多包含两个不同字符的最长子串 (双指针滑动窗口)

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

示例 1:

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

输入: "ccaabbb"
输出: 5
解释: t 是 "aabbb",长度为5。

 

滑动窗口,使用双指针,hashmap维护一个滑动窗口,窗口中至多只包含两个不同字符。

 

class Solution {
public:
    int lengthOfLongestSubstringTwoDistinct(string s) {
        unordered_map hashmap;
        int res = 0;
        for(int i=0,j=0;j2){
                if(hashmap[s[i]]>1) hashmap[s[i]]--;
                else if(hashmap[s[i]]==1) hashmap.erase(s[i]);
                i++;
            }
            res = max(res,j-i+1);
        }
        return res;
    }
};

 

你可能感兴趣的:(算法)