• 340. Longest Substring with At Most K Distinct Characters


        /*
         * 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;
            }
  • 相关阅读:
    [HEOI2014]南园满地堆轻絮
    [HEOI2016/TJOI2016]树
    初赛知识点
    [10.4模拟赛]T2
    [ZJOI2012]灾难
    [SDOI2010]古代猪文
    [9.26模拟赛]T1
    [9.26模拟赛]T3
    [9.26模拟赛]T2
    [9.19模拟赛]最小粒子数
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5659435.html
Copyright © 2020-2023  润新知