Leetcode-159.Longest Substring with At Most Two Distinct Characters

Problem Description

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.


Analysis:
We can use a nice sliding window mechanism to solve the problem.
We set :
l is left position of the window
j is last position of the other char(different with s[i], right boundary) in the window.
We don’t need to set the right boundary of the window, actually the index I imply the boundary.
1. When we met a character s[i] == s[i - 1], we don’t need to do anything, just moving forward the index i.
2. When we met a character which not equal with s[i -1], we have to consider this character is equal with the other character(index j) or not. If it’s true, we need update the index j, now the j = i - 1. Otherwise we should update the left boundary and index j.

l = j + 1,  j = i - 1; 

At last we have to consider the case that the number of distinct characters in string are less than 2.

这里写图片描述


Here comes the code :

int lengthOfLongestSubstringTwoDistinct(string s) 
 {
    int l = 0, j = -1, len = 0, n = s.size();
          for (int i = 1; i < n; i++) {
            if (s[i] == s[i - 1]) continue;
              if (j >= 0 && s[i] != s[j]) // compare with the other char
              {
                  len = max(len, i - l); //update the max len.
                  l = j + 1;             // update the left boundary, 
              }
            j = i - 1;                   // update the pos of the other char
         }
         return max(n - l, len);
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值