159. Longest Substring with At Most Two Distinct Characters

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.


Task is that we should find the longest substring which only has two characters but get the two appear as many times as possible.

First Thought

The most important idea in solving this kind of questions is "how to update the "start" pointer".

int lengthOfLongestSubstringTwoDistinct(string s) {
  if(s.length() <= 2) return s.length();
  vector<int> dict(256, -1);
  int count = 0, maxLength = 0, start = 0;
  char prev;
  for(int i = 0; i < s.length(); i++){
    if(prev != s[i]){ //chars not the same as the current one
      if(count < 2){ // found new chars in substr
        count++;
        dict[s[i]] = i;
        maxLength = max(maxLength, i-start+1);
      }else if(count == 2 && dict[s[i]] >= 0){ // char already exist in substr
        dict[s[i]] = i;
        maxLength = max(maxLength, i-start+1);
      }else if(dict[s[i]] < 0){ // third char
        maxLength = max(maxLength, i-start);
        start = dict[prev];
        dict[s[dict[prev]-1]] = -1;
        dict[s[i]] = i;
      }
      prev = s[i];
    }else{
      maxLength = max(maxLength, i-start+1);
    }
  }
  return maxLength;
}

Second Solution

Two Pointers. Still O(N), but hard to extend to k distinct characters substring.

int lengthOfLongestSubstringTwoDistinct(string s){
  int first = 0, second = -1;
  int maxLength = 0;
  for(int i = 1; i < s.length(); i++){
    if(s[i-1] == s[i]) continue;
    if(second > -1 && s[i] != s[second]){
      maxLength = max(maxLength, i-first);
      first = second+1;
    }
    second = i - 1;
  }
  return maxLength > (s.size() - first) ? maxLength : s.size() - first;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容