[?]*Longest Substring with At Most Two Distinct Characters

这也能算hard题……

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.

public class Solution {
    public int lengthOfLongestSubstringTwoDistinct(String s) 
    {
        int len = s.length();
        int max_len = 0;
        for (int i=0;i<len;i++)
        {
            HashSet<Character> set = new HashSet<Character>();
            int k = i;
            int j = i;
            for (; j<len; j++)
            {
                char c = s.charAt(j);
                if(!set.contains(c))
                {
                    if(set.size()<2)
                    {
                        set.add(c);
                    }
                    else
                    {
                        break;
                    }
                }
                
            }        
            max_len = Math.max(max_len,j-k);            
        }
        return max_len;       
    }
}

如何优化?

原文地址:https://www.cnblogs.com/hygeia/p/5074814.html