340. Longest Substring with At Most K Distinct Characters - Hard

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.
 

159. Longest Substring with At Most Two Distinct Characters - Hard 的generalized版本,当counter > k 时进入while循环

time: O(n), space: O(n)

class Solution {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        Map<Character, Integer> map = new HashMap<>();
        int slow = 0, fast = 0, counter = 0, d = 0;
        
        while(fast < s.length()) {
            char c = s.charAt(fast);
            map.put(c, map.getOrDefault(c, 0) + 1);
            if(map.get(c) == 1)
                counter++;
            fast++;
            
            while(counter > k) {
                char tmp = s.charAt(slow);
                map.put(tmp, map.get(tmp) - 1);
                if(map.get(tmp) == 0)
                    counter--;
                slow++;
            }
            d = Math.max(d, fast - slow);
        }
        return d;
    }
}

 

另一种写法:

class Solution {
    public int lengthOfLongestSubstringKDistinct(String s, int k) {
        if(s == null || s.length() == 0) {
            return 0;
        }
        Map<Character, Integer> map = new HashMap<>();
        int slow = 0, fast = 0, counter = 0, len = 0;
        while(fast < s.length()) {
            char f = s.charAt(fast);
            map.put(f, map.getOrDefault(f, 0) + 1);
            fast++;
            
            while(map.size() > k) {
                char c = s.charAt(slow);
                map.put(c, map.get(c) - 1);
                if(map.get(c) == 0) {
                    map.remove(c);
                }
                slow++;
            }
            len = Math.max(len, fast - slow);
        }
        return len;
    }
}

 

posted @ 2019-01-22 10:30  fatttcat  阅读(165)  评论(0编辑  收藏  举报