LeetCode 159. Longest Substring with At Most Two Distinct Characters

#include <string>
#include <iostream>
#include <vector>
#include <climits>
using namespace std;

/*
  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.
*/

// Set up two pointers until reach the third characters.
int lengthOfLongestSubstringTwoDistinct(string s) {
  int maxSize = 0;
  int pos_1 = -1;
  int pos_2 = -1;
  int start = 0;
  for(int i = 0; i < s.size(); ++i) {
    if(pos_1 == -1) {
      pos_1 = i;
    } else if(pos_2 == -1 && s[i] == s[pos_1]) {
      pos_1 = i;
    } else if(pos_2 == -1 && s[i] != s[pos_1]) {
      pos_2 = i;
    } // till now we have found two characters. pos_1 points to first one, pos_2 points to second one.
    else {
      if(s[i] == s[pos_2]) {
        pos_2 = i;   // repeat of the second char, thus, keep on going.
      } else if(s[i] == s[pos_1]) {
        // repeat of the first char, thus, update the first pointer points to the second
        // update the second pointer points to the first.
        pos_1 = pos_2;
        pos_2 = i;
      } else {
        // found the third char, update the start index.
        // update the first pointer points to the second char.
        // update the second pointer points to the third char.
        // maintain a window size of two different chars.
        start = pos_1;
        pos_1 = pos_2;
        pos_2 = i;   // update pos_2 points to the new char.
      }
    }
    maxSize = max(maxSize, i - start + 1);
  }
  return maxSize;
}

int main(void) {
  cout << lengthOfLongestSubstringTwoDistinct("eeeeecccceba") << endl;
}
 

你可能感兴趣的:(LeetCode 159. Longest Substring with At Most Two Distinct Characters)