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.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-with-at-most-two-distinct-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
int len = s.length();
if(len<3) return len;
int ans = 0;
int[] count = new int[256];
int L=0, R=0;
int num = 0;
while(R < len){
if(count[s.charAt(R)]==0) num++;
count[s.charAt(R)]++;
while(num > 2){
count[s.charAt(L)]--;
if(count[s.charAt(L)] == 0) --num;
L++;
}
R++;
ans = Math.max(ans, R-L);
}
return ans;
}
}