码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-12-25 06:25:56      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

这也能算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;       
    }
}

如何优化?

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

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!