-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathProblem_37.java
More file actions
63 lines (53 loc) · 2.5 KB
/
Problem_37.java
File metadata and controls
63 lines (53 loc) · 2.5 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
package strings;
import java.util.HashMap;
// Find the smallest window in a string containing all characters of another string
public class Problem_37 {
public static String findMinWindow(String s, String t) {
if (s == null || t == null || t.isEmpty()) {
return "";
}
// Count occurrences of each character in the target string
HashMap<Character, Integer> charCount = new HashMap<>();
for (char c : t.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
// Initialize variables for tracking the window
int windowStart = 0, minWindowLength = Integer.MAX_VALUE, count = 0;
// Slide the window across the string
for (int windowEnd = 0; windowEnd < s.length(); windowEnd++) {
char endChar = s.charAt(windowEnd);
// If the character is in the target string, increment the count
if (charCount.containsKey(endChar)) {
charCount.put(endChar, charCount.get(endChar) - 1);
if (charCount.get(endChar) >= 0) {
count++; // Found a character needed by the target string
}
}
// Shrink the window if all characters from the target string are found
while (count == t.length()) {
int currentWindowLength = windowEnd - windowStart + 1;
if (currentWindowLength < minWindowLength) {
minWindowLength = currentWindowLength;
// Update the window to reflect the smallest valid window so far
}
char startChar = s.charAt(windowStart);
if (charCount.containsKey(startChar)) {
if (charCount.get(startChar) == 0) {
count--; // Lost a character needed by the target string
}
charCount.put(startChar, charCount.get(startChar) + 1);
}
windowStart++;
}
}
// Return the smallest window if found, otherwise an empty string
return minWindowLength != Integer.MAX_VALUE ? s.substring(windowStart, windowStart + minWindowLength) : "";
}
public static void main(String[] args) {
String s = "ADOBECODEBANC";
String t = "ABC";
String smallestWindow = findMinWindow(s, t);
System.out.println(
"Smallest window containing all characters of '" + t + "' in '" + s + "' is: " + smallestWindow);
}
}