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

340. Longest Substring with At Most K Distinct Characters

时间:2016-07-11 12:20:14      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

    /*
     * 340. Longest Substring with At Most K Distinct Characters
     * 2016-7-10 by Mingyang
     * 利用HashMap来做sliding window的做法非常好!
     */
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        Map<Character, Integer> map = new HashMap<>();
        int left = 0;
        int best = 0;
        for(int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if(!map.containsKey(c)){
                map.put(c,1);
            }else{
                map.put(c, map.get(c)+1);
            }
           // map.put(c, map.getOrDefault(c, 0) + 1);
            while (map.size() > k) {
                char leftChar = s.charAt(left);
                if (map.containsKey(leftChar)) {
                    map.put(leftChar, map.get(leftChar) - 1);                     
                    if (map.get(leftChar) == 0) { 
                        map.remove(leftChar);
                    }
                }
                left++;
            }
            best = Math.max(best, i - left + 1);
        }
        return best;
    } 
    //也可以这样写,都可以,一样的原理,不过个人更喜欢HashMap一点:
     public int lengthOfLongestSubstringKDistinct1(String s, int k) {
            int[] count = new int[256];
            int num = 0, i = 0, res = 0;
            for (int j = 0; j < s.length(); j++) {
                if (count[s.charAt(j)]++ == 0) num++;
                if (num > k) {
                    while (--count[s.charAt(i++)] > 0);
                    num--;
                }
                res = Math.max(res, j - i + 1);
            }
            return res;
        }

 

340. Longest Substring with At Most K Distinct Characters

标签:

原文地址:http://www.cnblogs.com/zmyvszk/p/5659435.html

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