zoukankan      html  css  js  c++  java
  • 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;
            }
  • 相关阅读:
    问题集
    第04次作业-树
    06-图
    05-查找
    04-树
    03-栈和队列
    02-线性表
    01-抽象数据类型
    C语言--总结报告
    C语言--函数嵌套
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5659435.html
Copyright © 2011-2022 走看看