[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;
    }
};
    原文作者:楷书
    原文地址: https://www.jianshu.com/p/a1efb0015327
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞