[LeetCode] 340. Longest Substring with At Most K Distinct Characters
Given a string, find the length of the longest substring T that contains at most k distinct characters.
For example, Given s =
“eceba”
and k = 2,
T is "ece" which its length is 3.
Thought process:
Sliding window. Use a hash map of character => integer to keep track of the count of each character in the current window.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class Solution { public int lengthOfLongestSubstringKDistinct(String s, int k) { Map<Character, Integer> map = new HashMap<>(); int i = 0; int longest = 0; for (int j = 0; j < s.length(); j++) { int count = map.getOrDefault(s.charAt(j), 0); map.put(s.charAt(j), count + 1); if (map.size() > k) { while (i < s.length() && map.size() > k) { char c = s.charAt(i); map.put(c, map.get(c) - 1); if (map.get(c) == 0) { map.remove(c); } i++; } } longest = Math.max(longest, j - i + 1); } return longest; } } |
Time complexity: O(n).
Comments
Post a Comment