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