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
|
public class Solution {
public String shortestSubstringContainingSet(String s, Set<Character> set) {
if (s == null || set == null || set.isEmpty() || s.length() < set.size()) {
return null;
}
Map<Character, Integer> charCount = new HashMap<>();
Map<Character, Integer> windowCount = new HashMap<>();
// Initialize the character count from set
for (char c : set) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
int left = 0, right = 0, minLength = Integer.MAX_VALUE, start = -1, matched = 0;
while (right < s.length()) {
char rightChar = s.charAt(right);
if (charCount.containsKey(rightChar)) {
windowCount.put(rightChar, windowCount.getOrDefault(rightChar, 0) + 1);
if (windowCount.get(rightChar).intValue() == charCount.get(rightChar).intValue()) {
matched++;
}
}
while (matched == charCount.size()) {
if (right - left + 1 < minLength) {
minLength = right - left + 1;
start = left;
}
char leftChar = s.charAt(left);
if (charCount.containsKey(leftChar)) {
if (windowCount.get(leftChar).intValue() == charCount.get(leftChar).intValue()) {
matched--;
}
windowCount.put(leftChar, windowCount.get(leftChar) - 1);
}
left++;
}
right++;
}
return start == -1 ? null : s.substring(start, start + minLength);
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.shortestSubstringContainingSet("figehaeci", Set.of('a', 'e', 'i'))); // Output: aeci
System.out.println(solution.shortestSubstringContainingSet("figehaeci", Set.of('x', 'y', 'z'))); // Output: null
}
}
|