-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongestSubstringWithAtMostKDistinctCharacters.java
42 lines (40 loc) · 1.35 KB
/
LongestSubstringWithAtMostKDistinctCharacters.java
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.namanh.two_pointers;
import java.util.HashMap;
import java.util.Map;
/**
* https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters
* Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct
* characters.
*
* S1: Use Map to store frequently of character
* S2: Put character into map, or increase frequently if it already exists
* S3: If map size over k, remove element from start index
* S4: Result is current index minus start index
*
* Time: O(n)
* Space: O(n)
*/
public class LongestSubstringWithAtMostKDistinctCharacters {
public int lengthOfLongestSubstringKDistinct(String s, int k) {
Map<Character, Integer> freq = new HashMap<>();
int n = s.length();
int start = 0;
int result = 0;
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
freq.put(c, freq.getOrDefault(c, 0) + 1);
while (freq.size() > k) {
char cTmp = s.charAt(start);
int fTmp = freq.get(cTmp);
if (fTmp == 1) {
freq.remove(cTmp);
} else {
freq.put(cTmp, fTmp - 1);
}
start++;
}
result = Math.max(result, i - start + 1);
}
return result;
}
}