【每日刷题】至多包含两个不同字符的最长子串

题目地址

https://leetcode-cn.com/problems/longest-substring-with-at-most-two-distinct-characters/

题目描述:至多包含两个不同字符的最长子串

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

示例:

例 1:

输入: “eceba”

输出: 3

解释: t 是 “ece”,长度为3。

例 2:

输入: “ccaabbb”

输出: 5

解释: t 是 “aabbb”,长度为5。

解答

这道题比较简单,双指针 + 哈希表。

class Solution {
public:
    int lengthOfLongestSubstringTwoDistinct(string s) {
        unordered_map<char,int> record;
        int res = 0;
        for( int i = 0, j; i < s.size(); i = j)
            for( j = i; j < s.size(); j++){
                record[s[j]]++;
                if( record.size() <= 2)
                   res = max( res, j - i + 1);
                else if( record.size() > 2)
                    while( i < j && record.size() > 2){
                        record[s[i]]--;
                        if( record[s[i]] == 0)
                            record.erase(s[i]);
                        i++;
                    }
            }
        return res;
    }
};

你可能感兴趣的:(每日刷题)