Given a string s , find the length of the longest substring t that contains at most 2 distinct characters.
Example 1:
Input: "eceba" Output: 3 Explanation: t is "ece" which its length is 3.
Example 2:
Input: "ccaabbb" Output: 5 Explanation: t is "aabbb" which its length is 5.
解題思路:
class Solution {
public:
int lengthOfLongestSubstringTwoDistinct(string s)
{
if(s.empty()) return 0 ;
int len = s.size() , posi = 0 , posj = 0 , res = 0;
unordered_map<char , int> fromItoJ ;
fromItoJ[s[0]]++ ;
while(posi <= posj && posj < len)
{
while( posj < len && fromItoJ.size() <= 2)
{
posj++ ;
fromItoJ[s[posj]]++;
}
if(posj - posi > res) res = posj - posi ;
while(posi <= posj && fromItoJ.size() > 2)
{
fromItoJ[s[posi]]-- ;
if(fromItoJ[s[posi]] == 0) fromItoJ.erase(s[posi]) ;
posi++ ;
}
}
if(posj - posi > res) res = posj - posi ;
return res ;
}
};