-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFindKLengthSubstringsWithNoRepeatedCharacters.java
More file actions
66 lines (52 loc) · 1.72 KB
/
FindKLengthSubstringsWithNoRepeatedCharacters.java
File metadata and controls
66 lines (52 loc) · 1.72 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package string;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Description: https://leetcode.com/problems/find-k-length-substrings-with-no-repeated-characters
* Difficulty: Medium
* Time complexity: O(n)
* Space complexity: O(1)
*/
public class FindKLengthSubstringsWithNoRepeatedCharacters {
private static final int ALPHABET_SIZE = 26;
public int numKLenSubstrNoRepeatsViaSet(String s, int k) {
if (k > ALPHABET_SIZE) return 0;
Set<Character> seen = new HashSet<>();
int substrings = 0;
int left = 0;
for (int right = 0; right < s.length(); right++) {
while (seen.contains(s.charAt(right))) {
seen.remove(s.charAt(left));
left++;
}
seen.add(s.charAt(right));
if (right - left + 1 == k) {
substrings++;
seen.remove(s.charAt(left));
left++;
}
}
return substrings;
}
public int numKLenSubstrNoRepeatsViaFreqMap(String s, int k) {
if (k > ALPHABET_SIZE) return 0;
Map<Character, Integer> freqMap = new HashMap<>();
int substrings = 0;
int left = 0;
for (int right = 0; right < s.length(); right++) {
freqMap.merge(s.charAt(right), 1, Integer::sum);
while (freqMap.get(s.charAt(right)) > 1) {
freqMap.merge(s.charAt(left), -1, Integer::sum);
left++;
}
if (right - left + 1 == k) {
substrings++;
freqMap.merge(s.charAt(left), -1, Integer::sum);
left++;
}
}
return substrings;
}
}