-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinimum Window Substring
76 lines (68 loc) · 2.45 KB
/
Minimum Window Substring
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
67
68
69
70
71
72
73
74
75
76
// Minimum window substring - hard - 31/08/2023
// CodeStoryWithMIK
class Solution {
public String minWindow(String s, String t) {
if(s.length() < t.length()){
return "";
}
Map<Character, Integer> map = new HashMap<>();
for(int i=0; i<t.length(); i++){
map.put(t.charAt(i), map.getOrDefault(t.charAt(i), 0)+1);
}
int count = 0, start=0, min_length=Integer.MAX_VALUE, min_start = 0;
for(int end=0; end<s.length(); end++){
if(map.containsKey(s.charAt(end))){
if(map.get(s.charAt(end))>0){
count++;
}
map.put(s.charAt(end), map.get(s.charAt(end))-1);
}
if(count == t.length()){
while(start < end && (!map.containsKey(s.charAt(start)) || map.get(s.charAt(start))<0)){
if(map.containsKey(s.charAt(start))){
map.put(s.charAt(start), map.get(s.charAt(start))+1);
} start++;
}
if(min_length > end-start+1){
min_length = end-(min_start=start)+1;
}
if(map.containsKey(s.charAt(start))){
map.put(s.charAt(start), map.get(s.charAt(start))+1);
}
count--;
start++;
}
}
return min_length == Integer.MAX_VALUE?"":s.substring(min_start, min_start+min_length);
}
}
// Looks good
public String minWindow(String s, String t) {
if (s == null || t == null || s.length() ==0 || t.length() == 0 ||
s.length() < t.length()) {
return new String();
}
int[] map = new int[128];
int count = t.length();
int start = 0, end = 0, minLen = Integer.MAX_VALUE,startIndex =0;
for (char c :t.toCharArray()) {
map[c]++;
}
char[] chS = s.toCharArray();
while (end < chS.length) {
if (map[chS[end++]]-- >0) {
count--;
}
while (count == 0) {
if (end - start < minLen) {
startIndex = start;
minLen = end - start;
}
if (map[chS[start++]]++ == 0) {
count++;
}
}
}
return minLen == Integer.MAX_VALUE? new String():
new String(chS,startIndex,minLen);
}