[LeetCode][Two Pointers] 159. Longest Substring with At Most Two Distinct Characters

Problem

More LeetCode Discussions
Given a string, find the length of the longest substring T that contains at most 2 distinct characters.

For example, Given s = “eceba”,

T is "ece" which its length is 3.

Solution

采用双指针的思想,beg和end,每次end向右滑动一格,然后用hash记录字符数,如果当前substring.size() <= 2则记录,否则beg向右滑动一格,更新hash直到substring.size <= 2为止。

class Solution {
public:
    int lengthOfLongestSubstringTwoDistinct(string s) {
        if (s.size() == 0) {
            return 0;
        }
        int beg = 0;
        int end = 0;
        map<char, int> count;
        int maxLen = INT_MIN;
        for(int end = 0; end < s.size(); end++) {
            count[s[end]]++;
            while (count.size() > 2) {
                if (count[s[beg]] == 1) {
                    count.erase(count.find(s[beg]));
                } else {
                    count[s[beg]]--;
                }
                beg++;
            }
            maxLen = max(maxLen, end - beg + 1);
        }
        
        return maxLen;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容