zoukankan      html  css  js  c++  java
  • LeetCode——至多包含 K 个不同字符的最长子串

    Q:定一个字符串 s ,找出 至多 包含 k 个不同字符的最长子串 T。

    示例 1:
    输入: s = "eceba", k = 2
    输出: 3
    解释: 则 T 为 "ece",所以长度为 3。
    示例 2:
    输入: s = "aa", k = 1
    输出: 2
    解释: 则 T 为 "aa",所以长度为 2。

    A:滑动窗口

        public int lengthOfLongestSubstringKDistinct(String s, int k) {
            if (k == 0 || s.length() == 0) {
                return 0;
            }
            int maxLength = 0;
            int left = 0, right = 0;
            HashMap<Character, Integer> cMap = new HashMap<>();
            while (right < s.length()) {
                char r = s.charAt(right);
                cMap.put(r, cMap.getOrDefault(r, 0) + 1);
                if (cMap.keySet().size() <= k) {
                    maxLength = Math.max(maxLength, right - left + 1);
                } else {
                    while (left != right) {
                        char l = s.charAt(left++);
                        int lNum = cMap.get(l) - 1;
                        if (lNum == 0) {
                            cMap.remove(l);
                            break;
                        } else {
                            cMap.put(l, lNum);
                        }
                    }
                }
                right++;
            }
            return maxLength;
        }
    
  • 相关阅读:
    North North West
    HDU-5387 Clock
    HDU-1036 Average is not Fast Enough!
    Growling Gears
    HDU-5375 Gray code
    HDU-5373 The shortest problem
    hdu-5364 Distribution money
    UVA
    HDU-5363 Key Set
    HDU-5326 Work
  • 原文地址:https://www.cnblogs.com/xym4869/p/13418094.html
Copyright © 2011-2022 走看看