zoukankan      html  css  js  c++  java
  • leetcode340

    Given a string, find the length of the longest substring T that contains at most k distinct characters.
    Example 1:
    Input: s = "eceba", k = 2
    Output: 3
    Explanation: T is "ece" which its length is 3.
    Example 2:
    Input: s = "aa", k = 1
    Output: 2
    Explanation: T is "aa" which its length is 2.

    同向双指针。sliding window + count Map。O(n)
    i, j分别指针窗口头尾,一起向右挪动。map记录着每个字符出现过的次数,map.size()就是当前有多少种字符。
    1.当j没走到头就while循环。
    2.j慢慢增加,给map更新加入当前j位置字符后的字符统计情况。
    3.如果字符种类多出来了,右移i并减少map中的统计情况,直到把i移到让字符种类恢复正常。
    4.每个稳态打一次擂台。

    细节:
    1.每次写while循环的时候注意有没有改变()里的条件。你好几次忘记j++了笨蛋。

    实现:

    class Solution {
        public int lengthOfLongestSubstringKDistinct(String s, int k) {
            int ans = 0;
            if (s == null) {
                return ans;
            }
            
            Map<Character, Integer> counts = new HashMap<>();
            int i = 0, j = 0;
            while (j < s.length()) {
                char cj = s.charAt(j);
                counts.put(cj, counts.getOrDefault(cj, 0) + 1);
                while (counts.size() > k) {
                    char ci = s.charAt(i++);
                    if (counts.get(ci) == 1) {
                        counts.remove(ci);
                    } else {
                        counts.put(ci, counts.get(ci) - 1);
                    }
                }
                ans = Math.max(ans, j - i + 1);
                // P1: 别忘了动j,写完while后先写这行好了。
                j++;
            }
            return ans;
        }
    }
  • 相关阅读:
    开课 博客
    给定数组求数组中和最大子数组的和
    课堂测验
    读梦断代码有感(3)2019.2.20
    读梦断代码有感(2)2019.2.10
    读梦断代码有感(1)2019.2.05
    进度七
    进度 六
    sjz地铁作业
    进度四
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9668531.html
Copyright © 2011-2022 走看看