340. Longest Substring with At Most K Distinct Characters
Given a string, find the longest substring that contains only two unique characters. For example, given "abcbbbbcccbdddadacb", the longest substring that contains k unique character is "bcbbbbcccb".
分析:
用hashmap记录每个character从start到当前位置出现的次数,如果第k + 1个character出现, 更新maxLength,我们需要把左边的pointer(start) 往右移,直到从start到current之间只有K个character.
1 public class Solution { 2 public int lengthOfLongestSubstringKDistinct(String s, int k) { 3 if (s == null) return 0; 4 if (s.length() <= k) return s.length(); 5 6 int begin = 0, end = 0; 7 Map<Character, Integer> map = new HashMap<>(); 8 int tempMaxLength = Integer.MIN_VALUE; 9 10 while (end < s.length()) { 11 map.put(s.charAt(end), map.getOrDefault(s.charAt(end), 0) + 1); 12 while (map.size() > k) { 13 if (map.get(s.charAt(begin)) == 1) { 14 map.remove(s.charAt(begin)); 15 } else { 16 map.put(s.charAt(begin), map.get(s.charAt(begin)) - 1); 17 } 18 begin++; 19 } 20 tempMaxLength = Math.max(tempMaxLength, end - begin + 1); 21 end++; 22 } 23 return tempMaxLength; 24 } 25 }