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