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;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值