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.


因为最多只能有两个不一样的字符,所以首先我们用

char a 来存储除了当前字符之外的另一个字符, 

int result 来记录到当前位置所遇到的最长的满足条件的字符串长度,

int conti 来记录,从当前的字符开始往前有多少几个连续的字符

int cur 来记录当前的连续字符串长度


所以我们大体上会遇到三种情况,括号是当前遇到的字符

1: ab(b) 这个字符与上一个字符一样,所以conti++, cur++

2: ab(a) 当前字符是另外一个字符,但是不与上一个连续,cur++,conti = 1

3: baa(c) 当前字符与哪个都不一样,这时候 cur = 1+conti, conti = 1, a = s[i-1]

最后返回result结果即刻.

代码如下:

class Solution {
public:
    int lengthOfLongestSubstringTwoDistinct(string s) {
        //find the first two different characters
        char a = s[0];
        int idx = 0;
        while (idx < s.size() && s[idx] == a)
            idx++;
        
        if (idx >= s.size())
            return s.size();
        
        int result = idx+1;
        int cur = result;
        int conti = 1;
        
        //start loop
        for (int i = idx+1; i < s.size(); i++) {
            if (s[i] == s[i-1]) {
                cur++;
                conti++;
            } else if (s[i] == a){
                conti = 1;
                cur++;
                a = s[i-1];
            } else {
                cur = conti+1;
                conti = 1;
                a = s[i-1];
            }
            
            result = max(result,cur);
        }
        return result;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值