-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram125.java
More file actions
64 lines (49 loc) · 2.19 KB
/
Program125.java
File metadata and controls
64 lines (49 loc) · 2.19 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
import java.util.*;
public class Program125 {
//Minimum Window Substring -Given strings s and t, find the smallest window in s that contains all characters of t.
public static String minWindow(String s, String t) {
if (s.length() < t.length()) {
return "";
}
Map<Character, Integer> need = new HashMap<>(); // Required character counts
Map<Character, Integer> window = new HashMap<>(); // Current window character counts
// Count frequency of each char in t
for (char c : t.toCharArray()) {
need.put(c, need.getOrDefault(c, 0) + 1);
}
int left = 0, right = 0;
int required = need.size(); // Total unique characters needed
int formed = 0; // How many required characters are currently satisfied
int minLen = Integer.MAX_VALUE;
int start = 0;
while (right < s.length()) {
char c = s.charAt(right);
window.put(c, window.getOrDefault(c, 0) + 1);
// If the current character meets the required frequency
if (need.containsKey(c) && window.get(c).intValue() == need.get(c).intValue()) {
formed++;
}
// Try to shrink the window
while (left <= right && formed == required) {
if ((right - left + 1) < minLen) {
minLen = right - left + 1;
start = left;
}
char removeChar = s.charAt(left);
window.put(removeChar, window.get(removeChar) - 1);
// If removing breaks the requirement
if (need.containsKey(removeChar) && window.get(removeChar) < need.get(removeChar)) {
formed--;
}
left++;
}
right++;
}
return minLen == Integer.MAX_VALUE ? "" : s.substring(start, start + minLen);
}
public static void main(String[] args) {
String s = "ADOBECODEBANC";
String t = "ABC";
System.out.println("Minimum window containing all characters: " + minWindow(s, t));
}
}